import { getTranslations } from 'next-intl/server';

import { FischereiTabNavigation } from '@kit/fischerei/components';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

import { AccountNotFound } from '~/components/account-not-found';
import { CmsPageShell } from '~/components/cms-page-shell';

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

export default async function StatisticsPage({ params }: Props) {
  const { account } = await params;
  const client = getSupabaseServerClient();
  const t = await getTranslations('fischerei');

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

  if (!acct) return <AccountNotFound />;

  // Fetch actual statistics from existing tables
  const [watersResult, speciesResult, stockingResult, catchBooksResult, leasesResult, permitsResult] = await Promise.allSettled([
    client.from('waters').select('id', { count: 'exact' }).eq('account_id', acct.id),
    client.from('fish_species').select('id', { count: 'exact' }).eq('account_id', acct.id),
    client.from('fish_stocking').select('id, quantity, cost_total', { count: 'exact' }).eq('account_id', acct.id),
    client.from('catch_books').select('id, status', { count: 'exact' }).eq('account_id', acct.id),
    client.from('fishing_leases').select('id', { count: 'exact' }).eq('account_id', acct.id).eq('status', 'active'),
    client.from('fishing_permits').select('id', { count: 'exact' }).eq('account_id', acct.id),
  ]);

  const waterCount = watersResult.status === 'fulfilled' ? (watersResult.value.count ?? 0) : 0;
  const speciesCount = speciesResult.status === 'fulfilled' ? (speciesResult.value.count ?? 0) : 0;
  const stockingData = stockingResult.status === 'fulfilled' ? (stockingResult.value.data ?? []) : [];
  const stockingCount = stockingData.length;
  const stockingCost = stockingData.reduce((sum: number, s: any) => sum + (Number(s.cost_total) || 0), 0);
  const catchBookCount = catchBooksResult.status === 'fulfilled' ? (catchBooksResult.value.count ?? 0) : 0;
  const catchBookData = catchBooksResult.status === 'fulfilled' ? (catchBooksResult.value.data ?? []) : [];
  const pendingCatchBooks = catchBookData.filter((cb: any) => cb.status === 'submitted').length;
  const leaseCount = leasesResult.status === 'fulfilled' ? (leasesResult.value.count ?? 0) : 0;
  const permitCount = permitsResult.status === 'fulfilled' ? (permitsResult.value.count ?? 0) : 0;

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

  return (
    <CmsPageShell account={account} title={t('pages.statisticsTitle')}>
      <FischereiTabNavigation account={account} activeTab="statistics" />
      <div className="flex w-full flex-col gap-6">
        <div>
          <p className="text-muted-foreground">
            Fangstatistiken und Auswertungen
          </p>
        </div>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Gewässer</p><p className="text-2xl font-bold">{waterCount}</p></CardContent></Card>
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Fischarten</p><p className="text-2xl font-bold">{speciesCount}</p></CardContent></Card>
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Besatzaktionen</p><p className="text-2xl font-bold">{stockingCount}</p><p className="text-muted-foreground text-xs">{formatCurrency(stockingCost)} Gesamtkosten</p></CardContent></Card>
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Fangbücher</p><p className="text-2xl font-bold">{catchBookCount}</p>{pendingCatchBooks > 0 && <p className="text-xs text-amber-600">{pendingCatchBooks} zur Prüfung</p>}</CardContent></Card>
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Aktive Pachten</p><p className="text-2xl font-bold">{leaseCount}</p></CardContent></Card>
          <Card><CardContent className="p-6"><p className="text-muted-foreground text-sm">Erlaubnisscheine</p><p className="text-2xl font-bold">{permitCount}</p></CardContent></Card>
        </div>

        {waterCount === 0 && speciesCount === 0 && (
        <Card>
          <CardContent className="p-6">
            <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-8 text-center">
              <h3 className="text-lg font-semibold">Noch keine Daten vorhanden</h3>
              <p className="text-muted-foreground mt-1 max-w-sm text-sm">
                Sobald Gewässer, Fischarten und Fangbücher angelegt werden, erscheinen hier detaillierte Statistiken.
              </p>
            </div>
          </CardContent>
        </Card>
        )}
      </div>
    </CmsPageShell>
  );
}
