import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ArrowLeft, Scale, User, FileText, Receipt, DollarSign } from "lucide-react";
import { format } from "date-fns";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import UnitLedgerView from "@/components/unit-profile/UnitLedgerView";
import LegalCaseDocumentsTab from "@/components/legal/LegalCaseDocumentsTab";

type BreakdownFields = "assessments" | "lateFees" | "interest" | "adminFees" | "legalFees" | "violations" | "bankFees" | "payments";

const typeToField = (type: string): BreakdownFields => {
  const t = type.toLowerCase();
  if (t.includes("late")) return "lateFees";
  if (t.includes("interest")) return "interest";
  if (t.includes("admin")) return "adminFees";
  if (t.includes("legal")) return "legalFees";
  if (t.includes("violation")) return "violations";
  if (t.includes("bank")) return "bankFees";
  if (t.includes("payment") || t.includes("credit")) return "payments";
  return "assessments";
};

const fmt = (n: number) => "$" + Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: 2 });

const breakdownLabels: { key: BreakdownFields; label: string }[] = [
  { key: "assessments", label: "Assessments" },
  { key: "lateFees", label: "Late Fees" },
  { key: "interest", label: "Interest" },
  { key: "adminFees", label: "Admin Fees" },
  { key: "legalFees", label: "Legal Fees" },
  { key: "violations", label: "Violations" },
  { key: "bankFees", label: "Bank Fees" },
  { key: "payments", label: "Payments" },
];

export default function LegalCaseDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [matter, setMatter] = useState<any>(null);
  const [owners, setOwners] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [breakdown, setBreakdown] = useState<Record<BreakdownFields, number>>({
    assessments: 0, lateFees: 0, interest: 0, adminFees: 0, legalFees: 0, violations: 0, bankFees: 0, payments: 0
  });

  useEffect(() => {
    if (!id) return;
    const fetchData = async () => {
      setLoading(true);

      const { data: assignedAssociationIds } = await (supabase as any).rpc("get_legal_association_ids");
      const scopedAssociationIds = assignedAssociationIds || [];

      if (scopedAssociationIds.length === 0) {
        setMatter(null);
        setLoading(false);
        return;
      }

      const query = supabase
        .from("legal_matters")
        .select(`
          *,
          associations:association_id(name, address, city, state, zip, phone, email),
          units:unit_id(id, unit_number, address, association_id)
        `)
        .eq("id", id)
        .in("association_id", scopedAssociationIds);

      const { data: matterData, error: mError } = await query.single();

      if (mError) {
        console.error("Error fetching matter:", mError);
        setLoading(false);
        return;
      }

      setMatter(matterData);
      const isCollectionCase = matterData?.category === "collections" || matterData?.case_type === "collection" || !!matterData?.collection_id;

      // Fetch owners for the unit
      if (matterData?.unit_id) {
        const { data: ownerData } = await supabase
          .from("owners")
          .select("*")
          .eq("unit_id", matterData.unit_id)
          .neq("status", "archived")
          .order("created_at", { ascending: false });

        const ownersList = ownerData || [];
        setOwners(ownersList);

        // Fetch ledger entries for dues breakdown only on collection cases
        if (isCollectionCase && ownersList.length > 0) {
          const ownerIds = ownersList.map((o: any) => o.id);
          const { data: ledgerData } = await supabase
            .from("owner_ledger_entries")
            .select("owner_id, transaction_type, debit, credit")
            .in("owner_id", ownerIds);

          const bd: Record<BreakdownFields, number> = {
            assessments: 0, lateFees: 0, interest: 0, adminFees: 0, legalFees: 0, violations: 0, bankFees: 0, payments: 0
          };
          (ledgerData || []).forEach((entry: any) => {
            const field = typeToField(entry.transaction_type);
            if (field === "payments") {
              bd.payments += (entry.credit || 0) - (entry.debit || 0);
            } else {
              bd[field] += (entry.debit || 0) - (entry.credit || 0);
            }
          });
          setBreakdown(bd);
        }
      }

      setLoading(false);
    };

    fetchData();
  }, [id]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!matter) {
    return (
      <div className="text-center py-20 text-muted-foreground">
        <p>Case not found.</p>
        <Button variant="link" onClick={() => navigate("/legal")}>← Back to cases</Button>
      </div>
    );
  }

  const stageLabel = (matter.current_stage || "unknown").replace(/_/g, " ");
  const isCollectionCase = matter.category === "collections" || matter.case_type === "collection" || !!matter.collection_id;
  const totalDue = breakdown.assessments + breakdown.lateFees + breakdown.interest + breakdown.adminFees + breakdown.legalFees + breakdown.violations + breakdown.bankFees;
  const balance = totalDue - breakdown.payments;

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={() => navigate("/legal")} className="h-8 w-8">
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <Scale className="h-5 w-5 text-primary" />
            <h1 className="text-lg font-bold text-foreground">{matter.title}</h1>
            <Badge variant="outline" className="text-xs">{stageLabel}</Badge>
            {matter.has_payment_plan && <Badge variant="secondary" className="text-xs">Payment Plan</Badge>}
            {matter.is_bankruptcy && <Badge variant="destructive" className="text-xs">Bankruptcy</Badge>}
          </div>
          <p className="text-xs text-muted-foreground mt-0.5">
            {matter.associations?.name}
            {matter.units?.unit_number && ` · Unit ${matter.units.unit_number}`}
            {matter.units?.address && ` · ${matter.units.address}`}
          </p>
        </div>
      </div>

      {/* Owner Names & Address Summary */}
      {owners.length > 0 && (
        <Card>
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <User className="h-4 w-4 text-primary mt-0.5" />
              <div>
                <p className="font-semibold text-foreground text-sm">
                  {owners.map(o => `${o.first_name} ${o.last_name}`).join(", ")}
                </p>
                <p className="text-xs text-muted-foreground mt-0.5">
                  {matter.units?.address || owners[0]?.mailing_address || "No address on file"}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Dues Breakdown */}
      {isCollectionCase && (
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-3">
              <DollarSign className="h-4 w-4 text-primary" />
              <h3 className="font-semibold text-sm text-foreground">Dues Breakdown</h3>
            </div>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="text-xs">Category</TableHead>
                  <TableHead className="text-xs text-right">Amount</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {breakdownLabels.filter(b => b.key !== "payments").map(b => (
                  <TableRow key={b.key}>
                    <TableCell className="text-sm py-2">{b.label}</TableCell>
                    <TableCell className="text-sm text-right tabular-nums py-2">
                      {breakdown[b.key] > 0 ? fmt(breakdown[b.key]) : "—"}
                    </TableCell>
                  </TableRow>
                ))}
                <TableRow className="border-t-2">
                  <TableCell className="text-sm font-semibold py-2">Total Charges</TableCell>
                  <TableCell className="text-sm font-semibold text-right tabular-nums py-2">{fmt(totalDue)}</TableCell>
                </TableRow>
                <TableRow>
                  <TableCell className="text-sm py-2 text-primary">Payments Applied</TableCell>
                  <TableCell className="text-sm text-right tabular-nums py-2 text-primary">
                    {breakdown.payments > 0 ? `(${fmt(breakdown.payments)})` : "—"}
                  </TableCell>
                </TableRow>
                <TableRow className="border-t-2">
                  <TableCell className="text-sm font-bold py-2">Outstanding Balance</TableCell>
                  <TableCell className="text-sm font-bold text-right tabular-nums py-2 text-destructive">{fmt(balance)}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Case Summary */}
      <Card>
        <CardContent className="p-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            {matter.case_number && (
              <div>
                <span className="text-muted-foreground text-xs block">Case Number</span>
                <span className="font-medium text-foreground">{matter.case_number}</span>
              </div>
            )}
            {matter.official_case_name && (
              <div>
                <span className="text-muted-foreground text-xs block">Official Case Name</span>
                <span className="font-medium text-foreground">{matter.official_case_name}</span>
              </div>
            )}
            {matter.judge && (
              <div>
                <span className="text-muted-foreground text-xs block">Judge</span>
                <span className="font-medium text-foreground">{matter.judge}</span>
              </div>
            )}
            {matter.opposing_counsel && (
              <div>
                <span className="text-muted-foreground text-xs block">Opposing Counsel</span>
                <span className="font-medium text-foreground">{matter.opposing_counsel}</span>
              </div>
            )}
            {matter.attorney && (
              <div>
                <span className="text-muted-foreground text-xs block">Attorney</span>
                <span className="font-medium text-foreground">{matter.attorney}</span>
              </div>
            )}
            <div>
              <span className="text-muted-foreground text-xs block">Flags</span>
              <span className="font-medium text-foreground">
                {[matter.has_payment_plan && "Payment Plan", matter.is_bankruptcy && "Bankruptcy"].filter(Boolean).join(", ") || "—"}
              </span>
            </div>
            <div>
              <span className="text-muted-foreground text-xs block">Opened</span>
              <span className="font-medium text-foreground">
                {format(new Date(matter.opened_date || matter.created_at), "MMM d, yyyy")}
              </span>
            </div>
          </div>
          {matter.description && (
            <p className="text-sm text-muted-foreground mt-3 border-t pt-3">{matter.description}</p>
          )}
        </CardContent>
      </Card>

      {/* Tabs: Owner Info, Ledger, Documents */}
      <Tabs defaultValue="owner" className="w-full">
        <TabsList className="w-full justify-start">
          <TabsTrigger value="owner" className="gap-1.5 text-xs">
            <User className="h-3.5 w-3.5" /> Owner Information
          </TabsTrigger>
          {isCollectionCase && (
            <TabsTrigger value="ledger" className="gap-1.5 text-xs">
              <Receipt className="h-3.5 w-3.5" /> Account Ledger
            </TabsTrigger>
          )}
          <TabsTrigger value="documents" className="gap-1.5 text-xs">
            <FileText className="h-3.5 w-3.5" /> Documents
          </TabsTrigger>
        </TabsList>

        <TabsContent value="owner" className="mt-4">
          {owners.length === 0 ? (
            <Card>
              <CardContent className="py-10 text-center text-sm text-muted-foreground">
                No owner records found for this unit.
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-3">
              {owners.map((owner) => (
                <Card key={owner.id}>
                  <CardContent className="p-4">
                    <div className="flex items-start justify-between">
                      <div>
                        <h3 className="font-semibold text-foreground text-sm">
                          {owner.first_name} {owner.last_name}
                        </h3>
                        <div className="text-xs text-muted-foreground mt-1 space-y-0.5">
                          {owner.email && <p>Email: {owner.email}</p>}
                          {owner.phone && <p>Phone: {owner.phone}</p>}
                          {owner.mailing_address && <p>Mailing: {owner.mailing_address}</p>}
                          {owner.account_number && <p>Account #: {owner.account_number}</p>}
                        </div>
                      </div>
                      <Badge variant="outline" className="text-xs">
                        {owner.status || "active"}
                      </Badge>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>

        {isCollectionCase && (
          <TabsContent value="ledger" className="mt-4">
            {matter.unit_id ? (
              <UnitLedgerView unitId={matter.unit_id} associationId={matter.association_id} />
            ) : (
              <Card>
                <CardContent className="py-10 text-center text-sm text-muted-foreground">
                  No unit linked to this case. Ledger is unavailable.
                </CardContent>
              </Card>
            )}
          </TabsContent>
        )}

        <TabsContent value="documents" className="mt-4">
          {matter.unit_id ? (
            <LegalCaseDocumentsTab unitId={matter.unit_id} associationId={matter.association_id} />
          ) : (
            <Card>
              <CardContent className="py-10 text-center text-sm text-muted-foreground">
                No unit linked to this case. Documents are unavailable.
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
