import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { createFischereiApi } from '@kit/fischerei/api';
import { FischereiTabNavigation } from '@kit/fischerei/components';

import { CmsPageShell } from '~/components/cms-page-shell';
import { Badge } from '@kit/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@kit/ui/card';

import { LEASE_PAYMENT_LABELS } from '@kit/fischerei/lib/fischerei-constants';
import { AccountNotFound } from '~/components/account-not-found';

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

export default async function LeasesPage({ params, searchParams }: Props) {
  const { account } = await params;
  const search = await searchParams;
  const client = getSupabaseServerClient();

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

  if (!acct) return <AccountNotFound />;

  const api = createFischereiApi(client);
  const page = Number(search.page) || 1;
  const result = await api.listLeases(acct.id, {
    page,
    pageSize: 25,
  });

  return (
    <CmsPageShell account={account} title="Fischerei - Pachten">
      <FischereiTabNavigation account={account} activeTab="leases" />
      <div className="flex w-full flex-col gap-6">
        <div>
          <h1 className="text-2xl font-bold">Pachten</h1>
          <p className="text-muted-foreground">
            Gewässerpachtverträge verwalten
          </p>
        </div>
        <Card>
          <CardHeader>
            <CardTitle>Pachten ({result.total})</CardTitle>
          </CardHeader>
          <CardContent>
            {result.data.length === 0 ? (
              <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12 text-center">
                <h3 className="text-lg font-semibold">
                  Keine Pachten vorhanden
                </h3>
                <p className="mt-1 max-w-sm text-sm text-muted-foreground">
                  Erstellen Sie Ihren ersten Pachtvertrag.
                </p>
              </div>
            ) : (
              <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">Verpächter</th>
                      <th className="p-3 text-left font-medium">Gewässer</th>
                      <th className="p-3 text-left font-medium">Beginn</th>
                      <th className="p-3 text-left font-medium">Ende</th>
                      <th className="p-3 text-right font-medium">Jahresbetrag (€)</th>
                      <th className="p-3 text-left font-medium">Zahlungsart</th>
                    </tr>
                  </thead>
                  <tbody>
                    {result.data.map((lease: Record<string, unknown>) => {
                      const waters = lease.waters as Record<string, unknown> | null;
                      const paymentMethod = String(lease.payment_method ?? 'ueberweisung');

                      return (
                        <tr key={String(lease.id)} className="border-b hover:bg-muted/30">
                          <td className="p-3 font-medium">
                            {String(lease.lessor_name)}
                          </td>
                          <td className="p-3">
                            {waters ? String(waters.name) : '—'}
                          </td>
                          <td className="p-3">
                            {lease.start_date
                              ? new Date(String(lease.start_date)).toLocaleDateString('de-DE')
                              : '—'}
                          </td>
                          <td className="p-3">
                            {lease.end_date
                              ? new Date(String(lease.end_date)).toLocaleDateString('de-DE')
                              : 'unbefristet'}
                          </td>
                          <td className="p-3 text-right">
                            {lease.initial_amount != null
                              ? `${Number(lease.initial_amount).toLocaleString('de-DE', { minimumFractionDigits: 2 })} €`
                              : '—'}
                          </td>
                          <td className="p-3">
                            <Badge variant="outline">
                              {LEASE_PAYMENT_LABELS[paymentMethod] ?? paymentMethod}
                            </Badge>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </CmsPageShell>
  );
}
