import { useEffect, useState, useMemo } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeft, Building2, Mail, Phone, MapPin, FileText, DollarSign, Printer, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Separator } from "@/components/ui/separator";

interface Bill {
  id: string;
  invoice_number: string | null;
  bill_date: string;
  due_date: string | null;
  amount: number;
  amount_paid: number;
  status: string;
  paid_date: string | null;
  description: string | null;
  zoho_bill_id: string | null;
  zoho_payment_id: string | null;
  check_id: string | null;
  associations?: { name: string } | null;
  checks?: { check_number: string | null; check_date: string | null; bank_accounts?: { account_name: string } | null } | null;
}

interface Check {
  id: string;
  check_number: string | null;
  check_date: string | null;
  amount: number;
  memo: string | null;
  status: string;
  payee: string;
  bank_accounts?: { account_name: string } | null;
  associations?: { name: string } | null;
}

const statusColors: Record<string, string> = {
  pending: "bg-amber-100 text-amber-700",
  approved: "bg-emerald-100 text-emerald-700",
  paid: "bg-emerald-100 text-emerald-700",
  overdue: "bg-red-100 text-red-700",
  draft: "bg-muted text-muted-foreground",
  rejected: "bg-red-100 text-red-700",
  printed: "bg-emerald-100 text-emerald-700",
  void: "bg-muted text-muted-foreground",
};

export default function VendorDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [vendor, setVendor] = useState<any>(null);
  const [bills, setBills] = useState<Bill[]>([]);
  const [checks, setChecks] = useState<Check[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    (async () => {
      setLoading(true);
      try {
        const [vRes, bRes] = await Promise.all([
          supabase.from("vendors").select("*, associations(name)").eq("id", id).single(),
          supabase
            .from("bills")
            .select("id, invoice_number, bill_date, due_date, amount, amount_paid, status, paid_date, description, zoho_bill_id, zoho_payment_id, check_id, associations(name), checks:check_id(check_number, check_date, bank_accounts:bank_account_id(account_name))")
            .eq("vendor_id", id)
            .order("bill_date", { ascending: false }),
        ]);

        if (vRes.error) throw vRes.error;
        setVendor(vRes.data);
        setBills((bRes.data || []) as any);

        // Pull checks: any directly linked from bills + any payee match
        const linkedCheckIds = (bRes.data || []).map((b: any) => b.check_id).filter(Boolean);
        const vendorName = (vRes.data as any)?.name || "";
        const orFilter = vendorName
          ? `id.in.(${linkedCheckIds.length ? linkedCheckIds.join(",") : "00000000-0000-0000-0000-000000000000"}),payee.eq.${vendorName}`
          : `id.in.(${linkedCheckIds.length ? linkedCheckIds.join(",") : "00000000-0000-0000-0000-000000000000"})`;
        const { data: cData } = await supabase
          .from("checks")
          .select("id, check_number, check_date, amount, memo, status, payee, bank_accounts:bank_account_id(account_name), associations(name)")
          .or(orFilter)
          .order("check_date", { ascending: false });
        setChecks((cData || []) as any);
      } catch (err: any) {
        toast({ variant: "destructive", title: "Error loading vendor", description: err.message });
      } finally {
        setLoading(false);
      }
    })();
  }, [id, toast]);

  const totals = useMemo(() => {
    const totalBilled = bills.reduce((s, b) => s + Number(b.amount || 0), 0);
    const totalPaid = bills.filter((b) => b.status === "paid").reduce((s, b) => s + Number(b.amount || 0), 0);
    const outstanding = totalBilled - totalPaid;
    const totalChecks = checks.reduce((s, c) => s + Number(c.amount || 0), 0);
    return { totalBilled, totalPaid, outstanding, totalChecks };
  }, [bills, checks]);

  // Combined ledger view (chronological)
  const ledger = useMemo(() => {
    const rows: Array<{ date: string; type: string; ref: string; description: string; debit: number; credit: number; status: string; link?: string }> = [];
    bills.forEach((b) => {
      rows.push({
        date: b.bill_date,
        type: "Bill",
        ref: b.invoice_number || `BILL-${b.id.slice(0, 8)}`,
        description: b.description || b.associations?.name || "—",
        debit: Number(b.amount || 0),
        credit: 0,
        status: b.status,
        link: `/dashboard/bills/${b.id}`,
      });
      if (b.status === "paid" && b.paid_date) {
        rows.push({
          date: b.paid_date,
          type: "Payment",
          ref: b.checks?.check_number ? `Check #${b.checks.check_number}` : (b.zoho_payment_id ? `Zoho ${b.zoho_payment_id.slice(0, 8)}` : "Payment"),
          description: `Payment for ${b.invoice_number || `Bill ${b.id.slice(0, 8)}`}${b.checks?.bank_accounts?.account_name ? ` (${b.checks.bank_accounts.account_name})` : ""}`,
          debit: 0,
          credit: Number(b.amount || 0),
          status: "paid",
          link: `/dashboard/bills/${b.id}`,
        });
      }
    });
    // Add unlinked checks (manual checks written to this vendor that aren't tied to a bill)
    const linkedCheckIds = new Set(bills.map((b) => b.check_id).filter(Boolean) as string[]);
    checks.forEach((c) => {
      if (linkedCheckIds.has(c.id)) return;
      rows.push({
        date: c.check_date || "",
        type: "Check",
        ref: c.check_number ? `Check #${c.check_number}` : `CHK-${c.id.slice(0, 8)}`,
        description: c.memo || `${c.associations?.name || ""} — ${c.bank_accounts?.account_name || ""}`,
        debit: 0,
        credit: Number(c.amount || 0),
        status: c.status,
      });
    });
    return rows.sort((a, b) => (b.date || "").localeCompare(a.date || ""));
  }, [bills, checks]);

  if (loading) {
    return <div className="flex justify-center py-24"><Loader2 className="h-8 w-8 animate-spin text-muted-foreground" /></div>;
  }

  if (!vendor) return <div className="p-6 text-center text-muted-foreground">Vendor not found.</div>;

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold text-foreground">{vendor.name}</h1>
          <p className="text-sm text-muted-foreground">{vendor.contact_name || "Vendor profile"}</p>
        </div>
        {vendor.is_active ? (
          <Badge className="bg-emerald-100 text-emerald-700">Active</Badge>
        ) : (
          <Badge className="bg-muted text-muted-foreground">Inactive</Badge>
        )}
      </div>

      {/* Summary cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-xs uppercase font-semibold text-muted-foreground">Total Billed</p>
            <p className="text-xl font-bold mt-1">${totals.totalBilled.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs uppercase font-semibold text-muted-foreground">Total Paid</p>
            <p className="text-xl font-bold mt-1 text-emerald-600">${totals.totalPaid.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs uppercase font-semibold text-muted-foreground">Outstanding</p>
            <p className="text-xl font-bold mt-1 text-amber-600">${totals.outstanding.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs uppercase font-semibold text-muted-foreground">Checks Issued</p>
            <p className="text-xl font-bold mt-1">{checks.length} <span className="text-sm font-normal text-muted-foreground">/ ${totals.totalChecks.toLocaleString("en-US", { minimumFractionDigits: 2 })}</span></p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Vendor info */}
        <Card className="lg:col-span-1">
          <CardHeader><CardTitle className="text-base">Contact Info</CardTitle></CardHeader>
          <CardContent className="space-y-3 text-sm">
            {vendor.email && <div className="flex items-start gap-2"><Mail className="h-4 w-4 text-muted-foreground mt-0.5" /><span>{vendor.email}</span></div>}
            {vendor.phone && <div className="flex items-start gap-2"><Phone className="h-4 w-4 text-muted-foreground mt-0.5" /><span>{vendor.phone}</span></div>}
            {vendor.address && <div className="flex items-start gap-2"><MapPin className="h-4 w-4 text-muted-foreground mt-0.5" /><span className="whitespace-pre-line">{vendor.address}</span></div>}
            {vendor.tax_id && <div><span className="text-xs uppercase font-semibold text-muted-foreground">Tax ID:</span> <span className="ml-1">{vendor.tax_id}</span></div>}
            {vendor.payment_terms && <div><span className="text-xs uppercase font-semibold text-muted-foreground">Terms:</span> <span className="ml-1">Net {vendor.payment_terms}</span></div>}
            {vendor.contract_end_date && (() => {
              const end = new Date(vendor.contract_end_date + "T00:00:00");
              const now = new Date();
              const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
              const diffDays = Math.floor((end.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
              const expiringOrExpired = diffDays <= 90;
              return (
                <div>
                  <span className="text-xs uppercase font-semibold text-muted-foreground">Contract End:</span>{" "}
                  <span className={`ml-1 ${expiringOrExpired ? "text-destructive font-semibold" : ""}`}>
                    {end.toLocaleDateString()}
                    {diffDays < 0 && ` (expired ${Math.abs(diffDays)} day${Math.abs(diffDays) === 1 ? "" : "s"} ago)`}
                    {diffDays >= 0 && diffDays <= 90 && ` (in ${diffDays} day${diffDays === 1 ? "" : "s"})`}
                  </span>
                </div>
              );
            })()}
            {vendor.insurance_expiration_date && (() => {
              const exp = new Date(vendor.insurance_expiration_date + "T00:00:00");
              const today = new Date(); today.setHours(0,0,0,0);
              const active = exp >= today;
              return (
                <div>
                  <span className="text-xs uppercase font-semibold text-muted-foreground">Insurance:</span>{" "}
                  {active ? (
                    <span className="ml-1 inline-flex items-center gap-1 text-emerald-600">
                      ✓ Active{vendor.insurance_carrier ? ` · ${vendor.insurance_carrier}` : ""} (exp {exp.toLocaleDateString()})
                    </span>
                  ) : (
                    <span className="ml-1 text-destructive font-semibold">Expired ({exp.toLocaleDateString()})</span>
                  )}
                  {vendor.insurance_document_url && (
                    <> · <a href={vendor.insurance_document_url} target="_blank" rel="noreferrer" className="text-primary hover:underline text-xs">View certificate</a></>
                  )}
                </div>
              );
            })()}
            {vendor.is_1099_eligible && <Badge variant="outline">1099 Eligible</Badge>}
            {vendor.zoho_contact_id && <div className="text-xs text-muted-foreground"><span className="font-semibold">Zoho:</span> {vendor.zoho_contact_id}</div>}
            <Separator />
            {vendor.associations?.name && (
              <div className="flex items-start gap-2"><Building2 className="h-4 w-4 text-muted-foreground mt-0.5" /><span>{vendor.associations.name}</span></div>
            )}
            {vendor.notes && <p className="text-muted-foreground italic whitespace-pre-line">{vendor.notes}</p>}
          </CardContent>
        </Card>

        {/* Ledger / bills / checks tabs */}
        <Card className="lg:col-span-2">
          <CardContent className="p-0">
            <Tabs defaultValue="ledger">
              <TabsList className="m-4">
                <TabsTrigger value="ledger">Ledger</TabsTrigger>
                <TabsTrigger value="bills">Bills ({bills.length})</TabsTrigger>
                <TabsTrigger value="checks">Checks ({checks.length})</TabsTrigger>
              </TabsList>

              <TabsContent value="ledger" className="px-4 pb-4">
                {ledger.length === 0 ? (
                  <p className="text-sm text-muted-foreground italic py-8 text-center">No activity yet.</p>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Date</TableHead>
                        <TableHead>Type</TableHead>
                        <TableHead>Reference</TableHead>
                        <TableHead>Description</TableHead>
                        <TableHead className="text-right">Charge</TableHead>
                        <TableHead className="text-right">Payment</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {ledger.map((row, i) => (
                        <TableRow key={i} className={row.link ? "cursor-pointer hover:bg-muted/40" : ""} onClick={() => row.link && navigate(row.link)}>
                          <TableCell className="whitespace-nowrap">{row.date || "—"}</TableCell>
                          <TableCell>
                            <Badge variant="outline" className="text-xs">{row.type}</Badge>
                          </TableCell>
                          <TableCell className="font-mono text-xs">{row.ref}</TableCell>
                          <TableCell className="text-sm">{row.description}</TableCell>
                          <TableCell className="text-right">{row.debit > 0 ? `$${row.debit.toFixed(2)}` : ""}</TableCell>
                          <TableCell className="text-right text-emerald-600">{row.credit > 0 ? `$${row.credit.toFixed(2)}` : ""}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </TabsContent>

              <TabsContent value="bills" className="px-4 pb-4">
                {bills.length === 0 ? (
                  <p className="text-sm text-muted-foreground italic py-8 text-center">No bills for this vendor.</p>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Date</TableHead>
                        <TableHead>Invoice #</TableHead>
                        <TableHead>Association</TableHead>
                        <TableHead>Check</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead className="text-right">Amount</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {bills.map((b) => (
                        <TableRow key={b.id} className="cursor-pointer hover:bg-muted/40" onClick={() => navigate(`/dashboard/bills/${b.id}`)}>
                          <TableCell>{b.bill_date}</TableCell>
                          <TableCell className="font-mono text-xs">{b.invoice_number || `BILL-${b.id.slice(0, 8)}`}</TableCell>
                          <TableCell>{b.associations?.name || "—"}</TableCell>
                          <TableCell>{b.checks?.check_number ? <span className="text-xs">#{b.checks.check_number}</span> : <span className="text-muted-foreground">—</span>}</TableCell>
                          <TableCell>
                            <Badge className={statusColors[b.status] || "bg-muted"}>{b.status}</Badge>
                          </TableCell>
                          <TableCell className="text-right">${Number(b.amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </TabsContent>

              <TabsContent value="checks" className="px-4 pb-4">
                {checks.length === 0 ? (
                  <p className="text-sm text-muted-foreground italic py-8 text-center">No checks issued to this vendor.</p>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Date</TableHead>
                        <TableHead>Check #</TableHead>
                        <TableHead>Bank Account</TableHead>
                        <TableHead>Memo</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead className="text-right">Amount</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {checks.map((c) => (
                        <TableRow key={c.id}>
                          <TableCell>{c.check_date || "—"}</TableCell>
                          <TableCell className="font-mono text-xs">{c.check_number || "—"}</TableCell>
                          <TableCell>{c.bank_accounts?.account_name || "—"}</TableCell>
                          <TableCell className="text-sm">{c.memo || "—"}</TableCell>
                          <TableCell><Badge className={statusColors[c.status] || "bg-muted"}>{c.status}</Badge></TableCell>
                          <TableCell className="text-right">${Number(c.amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
