import Link from 'next/link';

import { Landmark, FileText, Euro, ArrowRight, Plus } from 'lucide-react';

import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Badge } from '@kit/ui/badge';
import { Button } from '@kit/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

import { createFinanceApi } from '@kit/finance/api';

import { CmsPageShell } from '~/components/cms-page-shell';
import { EmptyState } from '~/components/empty-state';
import { StatsCard } from '~/components/stats-card';
import { AccountNotFound } from '~/components/account-not-found';
import {
  BATCH_STATUS_VARIANT,
  BATCH_STATUS_LABEL,
  INVOICE_STATUS_VARIANT,
  INVOICE_STATUS_LABEL,
} from '~/lib/status-badges';

interface PageProps {
  params: Promise<{ account: string }>;
}

export default async function FinancePage({ params }: PageProps) {
  const { account } = await params;
  const client = getSupabaseServerClient();

  const { data: acct } = await client
    .from('accounts')
    .select('id')
    .eq('slug', account)
    .single();

  if (!acct) return <AccountNotFound />;

  const api = createFinanceApi(client);

  const [batches, invoices] = await Promise.all([
    api.listBatches(acct.id),
    api.listInvoices(acct.id),
  ]);

  const openAmount = invoices
    .filter(
      (inv: Record<string, unknown>) =>
        inv.status === 'sent' || inv.status === 'overdue',
    )
    .reduce(
      (sum: number, inv: Record<string, unknown>) =>
        sum + (Number(inv.total_amount) || 0),
      0,
    );

  return (
    <CmsPageShell account={account} title="Finanzen">
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold">Finanzen</h1>
            <p className="text-muted-foreground">
              SEPA-Einzüge und Rechnungen
            </p>
          </div>
          <div className="flex gap-2">
            <Link href={`/home/${account}/finance/invoices/new`}>
              <Button variant="outline">
                <Plus className="mr-2 h-4 w-4" />
                Neue Rechnung
              </Button>
            </Link>
            <Link href={`/home/${account}/finance/sepa/new`}>
              <Button>
                <Plus className="mr-2 h-4 w-4" />
                Neuer SEPA-Einzug
              </Button>
            </Link>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          <StatsCard
            title="SEPA-Einzüge"
            value={batches.length}
            icon={<Landmark className="h-5 w-5" />}
          />
          <StatsCard
            title="Rechnungen"
            value={invoices.length}
            icon={<FileText className="h-5 w-5" />}
          />
          <StatsCard
            title="Offener Betrag"
            value={`${openAmount.toFixed(2)} €`}
            icon={<Euro className="h-5 w-5" />}
          />
        </div>

        {/* SEPA Batches */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>Letzte SEPA-Einzüge</CardTitle>
            <Link href={`/home/${account}/finance/sepa`}>
              <Button variant="ghost" size="sm">
                Alle anzeigen
                <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </Link>
          </CardHeader>
          <CardContent>
            {batches.length === 0 ? (
              <EmptyState
                icon={<Landmark className="h-8 w-8" />}
                title="Keine SEPA-Einzüge"
                description="Erstellen Sie Ihren ersten SEPA-Einzug."
                actionLabel="Neuer SEPA-Einzug"
                actionHref={`/home/${account}/finance/sepa/new`}
              />
            ) : (
              <div className="rounded-md border">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="p-3 text-left font-medium">Status</th>
                      <th className="p-3 text-left font-medium">Typ</th>
                      <th className="p-3 text-right font-medium">Betrag</th>
                      <th className="p-3 text-left font-medium">Datum</th>
                    </tr>
                  </thead>
                  <tbody>
                    {batches.map((batch: Record<string, unknown>) => (
                      <tr
                        key={String(batch.id)}
                        className="border-b hover:bg-muted/30"
                      >
                        <td className="p-3">
                          <Badge
                            variant={
                              BATCH_STATUS_VARIANT[String(batch.status)] ?? 'secondary'
                            }
                          >
                            {BATCH_STATUS_LABEL[String(batch.status)] ?? String(batch.status)}
                          </Badge>
                        </td>
                        <td className="p-3">
                          {batch.batch_type === 'direct_debit'
                            ? 'Lastschrift'
                            : 'Überweisung'}
                        </td>
                        <td className="p-3 text-right">
                          {batch.total_amount != null
                            ? `${Number(batch.total_amount).toFixed(2)} €`
                            : '—'}
                        </td>
                        <td className="p-3">
                          {batch.execution_date
                            ? new Date(String(batch.execution_date)).toLocaleDateString('de-DE')
                            : batch.created_at
                              ? new Date(String(batch.created_at)).toLocaleDateString('de-DE')
                              : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Invoices */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>Letzte Rechnungen</CardTitle>
            <Link href={`/home/${account}/finance/invoices`}>
              <Button variant="ghost" size="sm">
                Alle anzeigen
                <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </Link>
          </CardHeader>
          <CardContent>
            {invoices.length === 0 ? (
              <EmptyState
                icon={<FileText className="h-8 w-8" />}
                title="Keine Rechnungen"
                description="Erstellen Sie Ihre erste Rechnung."
                actionLabel="Neue Rechnung"
                actionHref={`/home/${account}/finance/invoices/new`}
              />
            ) : (
              <div className="rounded-md border">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="p-3 text-left font-medium">Nr.</th>
                      <th className="p-3 text-left font-medium">Empfänger</th>
                      <th className="p-3 text-right font-medium">Betrag</th>
                      <th className="p-3 text-left font-medium">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {invoices.map((invoice: Record<string, unknown>) => (
                      <tr
                        key={String(invoice.id)}
                        className="border-b hover:bg-muted/30"
                      >
                        <td className="p-3 font-mono text-xs">
                          <Link
                            href={`/home/${account}/finance/invoices/${String(invoice.id)}`}
                            className="hover:underline"
                          >
                            {String(invoice.invoice_number ?? '—')}
                          </Link>
                        </td>
                        <td className="p-3">
                          {String(invoice.recipient_name ?? '—')}
                        </td>
                        <td className="p-3 text-right">
                          {invoice.total_amount != null
                            ? `${Number(invoice.total_amount).toFixed(2)} €`
                            : '—'}
                        </td>
                        <td className="p-3">
                          <Badge
                            variant={
                              INVOICE_STATUS_VARIANT[String(invoice.status)] ??
                              'secondary'
                            }
                          >
                            {INVOICE_STATUS_LABEL[String(invoice.status)] ??
                              String(invoice.status)}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
