import Link from 'next/link';

import {
  Landmark,
  FileText,
  Euro,
  ArrowRight,
  Plus,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { getTranslations } from 'next-intl/server';

import { createFinanceApi } from '@kit/finance/api';
import { formatDate, formatCurrencyAmount } from '@kit/shared/dates';
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 { ListToolbar } from '@kit/ui/list-toolbar';

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

const PAGE_SIZE = 25;

interface PageProps {
  params: Promise<{ account: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}

function buildQuery(
  base: Record<string, string | undefined>,
  overrides: Record<string, string | number | undefined>,
): string {
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries({ ...base, ...overrides })) {
    if (value !== undefined && value !== '') {
      params.set(key, String(value));
    }
  }
  const qs = params.toString();
  return qs ? `?${qs}` : '';
}

export default async function FinancePage({ params, searchParams }: PageProps) {
  const { account } = await params;
  const search = await searchParams;
  const client = getSupabaseServerClient();
  const t = await getTranslations('finance');

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

  if (!acct) return <AccountNotFound />;

  const q = typeof search.q === 'string' ? search.q : undefined;
  const status = typeof search.status === 'string' ? search.status : undefined;
  const page = Math.max(1, Number(search.page) || 1);

  const api = createFinanceApi(client);

  const [batchesResult, invoicesResult] = await Promise.all([
    api.listBatches(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
    api.listInvoices(acct.id, { search: q, status, page, pageSize: PAGE_SIZE }),
  ]);

  const batches = batchesResult.data;
  const invoices = invoicesResult.data;

  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,
    );

  // Use the larger of the two totals for pagination
  const totalPages = Math.max(
    batchesResult.totalPages,
    invoicesResult.totalPages,
  );
  const safePage = page;

  const queryBase = { q, status };

  return (
    <CmsPageShell account={account} title={t('dashboard.title')}>
      <div className="flex w-full flex-col gap-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <p className="text-muted-foreground">{t('dashboard.subtitle')}</p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" asChild>
              <Link href={`/home/${account}/finance/invoices/new`}>
                <Plus className="mr-2 h-4 w-4" />
                {t('invoices.newInvoice')}
              </Link>
            </Button>
            <Button asChild>
              <Link href={`/home/${account}/finance/sepa/new`}>
                <Plus className="mr-2 h-4 w-4" />
                {t('nav.newBatch')}
              </Link>
            </Button>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          <StatsCard
            title={t('dashboard.sepaBatches')}
            value={batchesResult.total}
            icon={<Landmark className="h-5 w-5" />}
          />
          <StatsCard
            title={t('invoices.title')}
            value={invoicesResult.total}
            icon={<FileText className="h-5 w-5" />}
          />
          <StatsCard
            title={t('dashboard.openInvoices')}
            value={formatCurrencyAmount(openAmount)}
            icon={<Euro className="h-5 w-5" />}
          />
        </div>

        {/* Toolbar */}
        <ListToolbar
          searchPlaceholder={t('common.showAll')}
          filters={[
            {
              param: 'status',
              label: t('common.status'),
              options: [
                { value: '', label: t('common.noData') },
                { value: 'draft', label: t('status.draft') },
                { value: 'ready', label: t('sepa.newBatch') },
                { value: 'sent', label: t('status.sent') },
                { value: 'paid', label: t('status.paid') },
                { value: 'overdue', label: t('status.overdue') },
                { value: 'cancelled', label: t('status.cancelled') },
              ],
            },
          ]}
        />

        {/* SEPA Batches */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>
              {t('sepa.title')} ({batchesResult.total})
            </CardTitle>
            <Button variant="ghost" size="sm" asChild>
              <Link href={`/home/${account}/finance/sepa`}>
                {t('common.showAll')}
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
          </CardHeader>
          <CardContent>
            {batches.length === 0 ? (
              <EmptyState
                icon={<Landmark className="h-8 w-8" />}
                title={t('sepa.noBatches')}
                description={t('sepa.createFirst')}
                actionLabel={t('nav.newBatch')}
                actionHref={`/home/${account}/finance/sepa/new`}
              />
            ) : (
              <div className="overflow-x-auto rounded-md border">
                <table className="w-full min-w-[640px] text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b">
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('common.status')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('common.type')}
                      </th>
                      <th scope="col" className="p-3 text-right font-medium">
                        {t('common.amount')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('common.date')}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {batches.map((batch: Record<string, unknown>) => (
                      <tr
                        key={String(batch.id)}
                        className="hover:bg-muted/30 border-b"
                      >
                        <td className="p-3">
                          <Badge
                            variant={
                              BATCH_STATUS_VARIANT[String(batch.status)] ??
                              'secondary'
                            }
                          >
                            {t(BATCH_STATUS_LABEL_KEYS[String(batch.status)] ??
                              String(batch.status))}
                          </Badge>
                        </td>
                        <td className="p-3">
                          {batch.batch_type === 'direct_debit'
                            ? t('sepa.directDebit')
                            : t('sepa.creditTransfer')}
                        </td>
                        <td className="p-3 text-right">
                          {batch.total_amount != null
                            ? formatCurrencyAmount(batch.total_amount as number)
                            : '—'}
                        </td>
                        <td className="p-3">
                          {formatDate(
                            (batch.execution_date ?? batch.created_at) as
                              | string
                              | null,
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Invoices */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>
              {t('invoices.title')} ({invoicesResult.total})
            </CardTitle>
            <Button variant="ghost" size="sm" asChild>
              <Link href={`/home/${account}/finance/invoices`}>
                {t('common.showAll')}
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
          </CardHeader>
          <CardContent>
            {invoices.length === 0 ? (
              <EmptyState
                icon={<FileText className="h-8 w-8" />}
                title={t('invoices.noInvoices')}
                description={t('invoices.createFirst')}
                actionLabel={t('invoices.newInvoice')}
                actionHref={`/home/${account}/finance/invoices/new`}
              />
            ) : (
              <div className="overflow-x-auto rounded-md border">
                <table className="w-full min-w-[640px] text-sm">
                  <thead>
                    <tr className="bg-muted/50 border-b">
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('invoices.invoiceNumber')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('invoices.recipient')}
                      </th>
                      <th scope="col" className="p-3 text-right font-medium">
                        {t('common.amount')}
                      </th>
                      <th scope="col" className="p-3 text-left font-medium">
                        {t('common.status')}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {invoices.map((invoice: Record<string, unknown>) => (
                      <tr
                        key={String(invoice.id)}
                        className="hover:bg-muted/30 border-b"
                      >
                        <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
                            ? formatCurrencyAmount(
                                invoice.total_amount as number,
                              )
                            : '—'}
                        </td>
                        <td className="p-3">
                          <Badge
                            variant={
                              INVOICE_STATUS_VARIANT[String(invoice.status)] ??
                              'secondary'
                            }
                          >
                            {t(INVOICE_STATUS_LABEL_KEYS[String(invoice.status)] ?? String(invoice.status))}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between">
            <p className="text-muted-foreground text-sm">
              {t('common.page')} {safePage} {t('common.of')} {totalPages}
            </p>
            <div className="flex items-center gap-1">
              {safePage > 1 ? (
                <Button variant="outline" size="sm" asChild>
                  <Link
                    href={`/home/${account}/finance${buildQuery(queryBase, { page: safePage - 1 })}`}
                    aria-label={t('common.previous')}
                  >
                    <ChevronLeft className="h-4 w-4" aria-hidden="true" />
                  </Link>
                </Button>
              ) : (
                <Button variant="outline" size="sm" disabled aria-label={t('common.previous')}>
                  <ChevronLeft className="h-4 w-4" aria-hidden="true" />
                </Button>
              )}

              <span className="px-3 text-sm font-medium">
                {safePage} / {totalPages}
              </span>

              {safePage < totalPages ? (
                <Button variant="outline" size="sm" asChild>
                  <Link
                    href={`/home/${account}/finance${buildQuery(queryBase, { page: safePage + 1 })}`}
                    aria-label={t('common.next')}
                  >
                    <ChevronRight className="h-4 w-4" aria-hidden="true" />
                  </Link>
                </Button>
              ) : (
                <Button variant="outline" size="sm" disabled aria-label={t('common.next')}>
                  <ChevronRight className="h-4 w-4" aria-hidden="true" />
                </Button>
              )}
            </div>
          </div>
        )}
      </div>
    </CmsPageShell>
  );
}
