import Link from 'next/link';

import { Euro, CreditCard, TrendingUp, ArrowRight } from 'lucide-react';

import { createFinanceApi } from '@kit/finance/api';
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 { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';
import { StatsCard } from '~/components/stats-card';

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

const formatCurrency = (amount: number) =>
  new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(
    amount,
  );

export default async function PaymentsPage({ 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 [batchesResult, invoicesResult] = await Promise.all([
    api.listBatches(acct.id),
    api.listInvoices(acct.id),
  ]);
  const batches = batchesResult.data;
  const invoices = invoicesResult.data;

  const paidInvoices = invoices.filter(
    (inv: Record<string, unknown>) => inv.status === 'paid',
  );
  const openInvoices = invoices.filter(
    (inv: Record<string, unknown>) =>
      inv.status === 'sent' || inv.status === 'overdue',
  );
  const overdueInvoices = invoices.filter(
    (inv: Record<string, unknown>) => inv.status === 'overdue',
  );

  const paidTotal = paidInvoices.reduce(
    (sum: number, inv: Record<string, unknown>) =>
      sum + (Number(inv.total_amount) || 0),
    0,
  );

  const openTotal = openInvoices.reduce(
    (sum: number, inv: Record<string, unknown>) =>
      sum + (Number(inv.total_amount) || 0),
    0,
  );

  const overdueTotal = overdueInvoices.reduce(
    (sum: number, inv: Record<string, unknown>) =>
      sum + (Number(inv.total_amount) || 0),
    0,
  );

  const sepaTotal = batches.reduce(
    (sum: number, b: Record<string, unknown>) =>
      sum + (Number(b.total_amount) || 0),
    0,
  );

  return (
    <CmsPageShell account={account} title="Zahlungen">
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div>
          <h1 className="text-2xl font-bold">Zahlungsübersicht</h1>
          <p className="text-muted-foreground">
            Zusammenfassung aller Zahlungen und offenen Beträge
          </p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <StatsCard
            title="Bezahlt"
            value={formatCurrency(paidTotal)}
            icon={<Euro className="h-5 w-5" />}
            description={`${paidInvoices.length} Rechnungen`}
          />
          <StatsCard
            title="Offen"
            value={formatCurrency(openTotal)}
            icon={<CreditCard className="h-5 w-5" />}
            description={`${openInvoices.length} Rechnungen`}
          />
          <StatsCard
            title="Überfällig"
            value={formatCurrency(overdueTotal)}
            icon={<TrendingUp className="h-5 w-5" />}
            description={`${overdueInvoices.length} Rechnungen`}
          />
          <StatsCard
            title="SEPA-Einzüge"
            value={formatCurrency(sepaTotal)}
            icon={<Euro className="h-5 w-5" />}
            description={`${batches.length} Einzüge`}
          />
        </div>

        {/* Quick Links */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-base">Offene Rechnungen</CardTitle>
              <Badge
                variant={openInvoices.length > 0 ? 'default' : 'secondary'}
              >
                {openInvoices.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground mb-4 text-sm">
                {openInvoices.length > 0
                  ? `${openInvoices.length} Rechnungen mit einem Gesamtbetrag von ${formatCurrency(openTotal)} sind offen.`
                  : 'Keine offenen Rechnungen vorhanden.'}
              </p>
              <Link href={`/home/${account}/finance/invoices`}>
                <Button variant="outline" size="sm">
                  Rechnungen anzeigen
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Button>
              </Link>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-base">SEPA-Einzüge</CardTitle>
              <Badge variant={batches.length > 0 ? 'default' : 'secondary'}>
                {batches.length}
              </Badge>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground mb-4 text-sm">
                {batches.length > 0
                  ? `${batches.length} SEPA-Einzüge mit einem Gesamtvolumen von ${formatCurrency(sepaTotal)}.`
                  : 'Keine SEPA-Einzüge vorhanden.'}
              </p>
              <Link href={`/home/${account}/finance/sepa`}>
                <Button variant="outline" size="sm">
                  Einzüge anzeigen
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Button>
              </Link>
            </CardContent>
          </Card>
        </div>
      </div>
    </CmsPageShell>
  );
}
