import Link from 'next/link';

import { Euro, CreditCard, TrendingUp, ArrowRight } from 'lucide-react';
import { getTranslations } from 'next-intl/server';

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 t = await getTranslations('finance');
  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={t('payments.title')}>
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div>
          <p className="text-muted-foreground">{t('payments.subtitle')}</p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <StatsCard
            title={t('payments.statPaid')}
            value={formatCurrency(paidTotal)}
            icon={<Euro className="h-5 w-5" />}
            description={`${paidInvoices.length} ${t('payments.paidInvoices')}`}
          />
          <StatsCard
            title={t('payments.statOpen')}
            value={formatCurrency(openTotal)}
            icon={<CreditCard className="h-5 w-5" />}
            description={`${openInvoices.length} ${t('invoices.title')}`}
          />
          <StatsCard
            title={t('payments.statOverdue')}
            value={formatCurrency(overdueTotal)}
            icon={<TrendingUp className="h-5 w-5" />}
            description={`${overdueInvoices.length} ${t('invoices.title')}`}
          />
          <StatsCard
            title={t('payments.sepaBatches')}
            value={formatCurrency(sepaTotal)}
            icon={<Euro className="h-5 w-5" />}
            description={`${batches.length} ${t('payments.batchUnit')}`}
          />
        </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">
                {t('payments.openInvoices')}
              </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
                  ? t('payments.invoicesOpenSummary', {
                      count: openInvoices.length,
                      total: formatCurrency(openTotal),
                    })
                  : t('payments.noOpenInvoices')}
              </p>
              <Button variant="outline" size="sm" asChild>
                <Link href={`/home/${account}/finance/invoices`}>
                  {t('payments.viewInvoices')}
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Link>
              </Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-base">
                {t('payments.sepaBatches')}
              </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
                  ? t('payments.batchSummary', {
                      count: batches.length,
                      total: formatCurrency(sepaTotal),
                    })
                  : t('payments.noBatchesFound')}
              </p>
              <Button variant="outline" size="sm" asChild>
                <Link href={`/home/${account}/finance/sepa`}>
                  {t('payments.viewBatches')}
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Link>
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </CmsPageShell>
  );
}
