import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { trpc } from "@/lib/trpc";
import { buildSupplierBudgetSummary } from "@shared/invoiceAnalytics";
import { CalendarDays, Euro, FileText } from "lucide-react";
import { useMemo, useState } from "react";

const MONTHS = [
  ["01", "Janvier"], ["02", "Février"], ["03", "Mars"], ["04", "Avril"],
  ["05", "Mai"], ["06", "Juin"], ["07", "Juillet"], ["08", "Août"],
  ["09", "Septembre"], ["10", "Octobre"], ["11", "Novembre"], ["12", "Décembre"],
] as const;

function formatCurrency(value: number) {
  return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(value);
}

export default function RealBudget() {
  const currentYear = new Date().getFullYear();
  const [selectedYear, setSelectedYear] = useState(String(currentYear));
  const [selectedMonth, setSelectedMonth] = useState("all");
  const { data: invoices, isLoading } = trpc.invoices.list.useQuery();

  const availableYears = useMemo(() => {
    const years = new Set<number>([currentYear]);
    (invoices || []).forEach((invoice) => {
      const value = invoice.invoiceDate ?? invoice.createdAt;
      if (!value) return;
      const date = new Date(value);
      if (!Number.isNaN(date.getTime())) years.add(date.getFullYear());
    });
    return Array.from(years).sort((a, b) => b - a);
  }, [invoices, currentYear]);

  const rows = useMemo(
    () => buildSupplierBudgetSummary(invoices || [], selectedYear, selectedMonth),
    [invoices, selectedYear, selectedMonth],
  );
  const totals = useMemo(() => rows.reduce((total, row) => ({
    subscriptionAmount: total.subscriptionAmount + row.subscriptionAmount,
    nonSubscriptionAmount: total.nonSubscriptionAmount + row.nonSubscriptionAmount,
    totalAmount: total.totalAmount + row.totalAmount,
  }), { subscriptionAmount: 0, nonSubscriptionAmount: 0, totalAmount: 0 }), [rows]);

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold">Budget réel</h1>
          <p className="mt-1 text-muted-foreground">Montants réellement facturés, regroupés par fournisseur.</p>
        </div>

        <Card className="border-blue-100 bg-blue-50/70">
          <CardContent className="flex flex-wrap items-center gap-3 py-4">
            <div className="flex items-center gap-1.5 text-sm font-medium text-blue-700"><CalendarDays className="h-4 w-4" /> Période :</div>
            <Select value={selectedYear} onValueChange={(value) => { setSelectedYear(value); if (value === "all") setSelectedMonth("all"); }}>
              <SelectTrigger className="w-28 bg-white"><SelectValue placeholder="Année" /></SelectTrigger>
              <SelectContent><SelectItem value="all">Toute année</SelectItem>{availableYears.map((year) => <SelectItem key={year} value={String(year)}>{year}</SelectItem>)}</SelectContent>
            </Select>
            <Select value={selectedMonth} onValueChange={setSelectedMonth} disabled={selectedYear === "all"}>
              <SelectTrigger className="w-40 bg-white"><SelectValue placeholder="Mois" /></SelectTrigger>
              <SelectContent><SelectItem value="all">Tous les mois</SelectItem>{MONTHS.map(([value, label]) => <SelectItem key={value} value={value}>{label}</SelectItem>)}</SelectContent>
            </Select>
          </CardContent>
        </Card>

        <div className="grid gap-4 md:grid-cols-3">
          <Card><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">Abonnements</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-violet-700">{formatCurrency(totals.subscriptionAmount)}</div></CardContent></Card>
          <Card><CardHeader className="pb-2"><CardTitle className="text-sm font-medium">Hors abonnement</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-blue-700">{formatCurrency(totals.nonSubscriptionAmount)}</div></CardContent></Card>
          <Card><CardHeader className="pb-2"><CardTitle className="flex items-center gap-2 text-sm font-medium"><Euro className="h-4 w-4" /> Total facturé</CardTitle></CardHeader><CardContent><div className="text-2xl font-bold text-emerald-700">{formatCurrency(totals.totalAmount)}</div></CardContent></Card>
        </div>

        <Card>
          <CardHeader><CardTitle>Budget réel par fournisseur</CardTitle><CardDescription>Les factures finalisées sont séparées entre abonnements et hors abonnement.</CardDescription></CardHeader>
          <CardContent>
            {isLoading ? <div className="py-12 text-center text-muted-foreground">Chargement du budget…</div> : rows.length === 0 ? <div className="flex flex-col items-center gap-2 py-12 text-muted-foreground"><FileText className="h-10 w-10" />Aucune facture finalisée pour cette période.</div> : (
              <div className="overflow-x-auto rounded-lg border">
                <table className="w-full min-w-[850px] text-sm"><thead className="bg-muted/60 text-left text-muted-foreground"><tr><th className="px-4 py-3 font-medium">Fournisseur</th><th className="px-4 py-3 text-right font-medium">Abonnements</th><th className="px-4 py-3 text-right font-medium">Montant abonnements</th><th className="px-4 py-3 text-right font-medium">Hors abonnement</th><th className="px-4 py-3 text-right font-medium">Montant hors abonnement</th><th className="px-4 py-3 text-right font-medium">Total</th></tr></thead>
                  <tbody>{rows.map((row) => <tr key={row.supplierName} className="border-t hover:bg-muted/30"><td className="px-4 py-3 font-medium">{row.supplierName}</td><td className="px-4 py-3 text-right">{row.subscriptionCount}</td><td className="px-4 py-3 text-right text-violet-700">{formatCurrency(row.subscriptionAmount)}</td><td className="px-4 py-3 text-right">{row.nonSubscriptionCount}</td><td className="px-4 py-3 text-right text-blue-700">{formatCurrency(row.nonSubscriptionAmount)}</td><td className="px-4 py-3 text-right font-semibold">{formatCurrency(row.totalAmount)}</td></tr>)}</tbody>
                  <tfoot className="border-t-2 bg-muted/50 font-semibold"><tr><td className="px-4 py-3">Total</td><td colSpan={2} className="px-4 py-3 text-right text-violet-700">{formatCurrency(totals.subscriptionAmount)}</td><td colSpan={2} className="px-4 py-3 text-right text-blue-700">{formatCurrency(totals.nonSubscriptionAmount)}</td><td className="px-4 py-3 text-right text-emerald-700">{formatCurrency(totals.totalAmount)}</td></tr></tfoot>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
