import { createClient } from "@/lib/supabase/server";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Plus, Receipt, DollarSign, Clock, CheckCircle2, AlertCircle } from "lucide-react";
import { format } from "date-fns";
import { es } from "date-fns/locale";

export const dynamic = "force-dynamic";

const statusConfig: Record<string, { label: string; color: string; icon: any }> = {
  pending: { label: "Pendiente", color: "bg-amber-100 text-amber-700", icon: Clock },
  partial: { label: "Parcial", color: "bg-blue-100 text-blue-700", icon: AlertCircle },
  paid: { label: "Pagada", color: "bg-emerald-100 text-emerald-700", icon: CheckCircle2 },
};

export default async function BillingPage({ searchParams }: { searchParams: Promise<{ status?: string }> }) {
  const params = await searchParams;
  const supabase = await createClient();

  const { data: invoices } = await supabase
    .from("invoices")
    .select("*, patient:patients(id, first_name, last_name)")
    .order("created_at", { ascending: false })
    .limit(50);

  const all = invoices || [];
  const totalRevenue = all.filter(i => i.payment_status === "paid").reduce((s, i) => s + Number(i.total), 0);
  const totalPending = all.filter(i => i.payment_status !== "paid").reduce((s, i) => s + Number(i.total) - Number(i.paid_amount), 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Facturacion</h1>
          <p className="text-muted-foreground">Facturas, cobros y reportes financieros.</p>
        </div>
        <Link href="/billing/new"><Button className="gap-2"><Plus className="h-4 w-4" /> Nueva factura</Button></Link>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 sm:grid-cols-3">
        <Card>
          <CardContent className="p-4 flex items-center gap-4">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-emerald-100"><DollarSign className="h-5 w-5 text-emerald-600" /></div>
            <div><p className="text-sm text-muted-foreground">Cobrado</p><p className="text-2xl font-bold">${totalRevenue.toLocaleString("es-MX", { minimumFractionDigits: 2 })}</p></div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4 flex items-center gap-4">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-amber-100"><Clock className="h-5 w-5 text-amber-600" /></div>
            <div><p className="text-sm text-muted-foreground">Por cobrar</p><p className="text-2xl font-bold">${totalPending.toLocaleString("es-MX", { minimumFractionDigits: 2 })}</p></div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4 flex items-center gap-4">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-blue-100"><Receipt className="h-5 w-5 text-blue-600" /></div>
            <div><p className="text-sm text-muted-foreground">Total facturas</p><p className="text-2xl font-bold">{all.length}</p></div>
          </CardContent>
        </Card>
      </div>

      {/* Invoice Table */}
      {all.length === 0 ? (
        <Card className="flex flex-col items-center justify-center py-16">
          <Receipt className="h-12 w-12 text-muted-foreground/40 mb-4" />
          <h3 className="text-lg font-semibold">Sin facturas</h3>
          <p className="text-sm text-muted-foreground mb-4">Crea tu primera factura.</p>
          <Link href="/billing/new"><Button>Nueva factura</Button></Link>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Folio</TableHead>
                <TableHead>Paciente</TableHead>
                <TableHead>Fecha</TableHead>
                <TableHead className="text-right">Total</TableHead>
                <TableHead className="text-right">Pagado</TableHead>
                <TableHead>Estado</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {all.map((inv: any) => {
                const config = statusConfig[inv.payment_status] || statusConfig.pending;
                return (
                  <TableRow key={inv.id} className="cursor-pointer hover:bg-muted/50">
                    <TableCell className="font-mono text-sm">{inv.invoice_number}</TableCell>
                    <TableCell className="font-medium">{inv.patient?.first_name} {inv.patient?.last_name}</TableCell>
                    <TableCell className="text-muted-foreground text-sm">{format(new Date(inv.created_at), "dd/MM/yyyy")}</TableCell>
                    <TableCell className="text-right font-semibold">${Number(inv.total).toLocaleString("es-MX", { minimumFractionDigits: 2 })}</TableCell>
                    <TableCell className="text-right text-muted-foreground">${Number(inv.paid_amount).toLocaleString("es-MX", { minimumFractionDigits: 2 })}</TableCell>
                    <TableCell><Badge className={config.color} variant="secondary">{config.label}</Badge></TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </Card>
      )}
    </div>
  );
}
