import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Scale, Plus, Search, MapPin, DollarSign, Calendar, Building2, FileDown, Eye, Pencil, Trash2, Download } from "lucide-react";
import RecordImportButton from "@/components/RecordImportButton";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { format } from "date-fns";
import VotingAndComments from "@/components/shared/VotingAndComments";

const CASE_TYPES = ["Dispute", "Compliance", "Litigation", "Contract Review", "Collection", "Other"];
const STAGES = ["Intent to Lien", "Claim of Lien", "Lien Foreclosure", "Foreclosed", "Bankruptcy Hold", "Resolved", "Sent to Attorney"];

const stageColors: Record<string, string> = {
  "intent_to_lien": "bg-amber-100 text-amber-800",
  "claim_of_lien": "bg-orange-100 text-orange-800",
  "lien_foreclosure": "bg-red-100 text-red-800",
  "foreclosed": "bg-red-200 text-red-900",
  "bankruptcy_hold": "bg-rose-100 text-rose-800",
  "resolved": "bg-emerald-100 text-emerald-800",
  "sent_to_attorney": "bg-blue-100 text-blue-800",
};

const statusColors: Record<string, string> = {
  open: "bg-blue-100 text-blue-700",
  active: "bg-amber-100 text-amber-700",
  settled: "bg-emerald-100 text-emerald-700",
  closed: "bg-muted text-muted-foreground",
};

function toSlug(s: string) { return s.toLowerCase().replace(/\s+/g, "_"); }
function fromSlug(s: string) { return s.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase()); }

function normalizeLegalSaveState(stage: string, status: string) {
  const currentStage = toSlug(stage || "");
  return currentStage === "resolved" || status === "resolved"
    ? { current_stage: "resolved", status: "closed" }
    : { current_stage: currentStage, status };
}

function isArchivedLegalMatter(matter: any) {
  return matter.status === "closed" || matter.status === "archived";
}

function getMatterOwnerNames(matter: any) {
  return ((matter.units?.owners || []) as any[])
    .filter((owner) => owner?.status !== "archived")
    .map((owner) => `${owner.first_name || ""} ${owner.last_name || ""}`.trim())
    .filter(Boolean);
}

export default function LegalMattersPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [matters, setMatters] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [units, setUnits] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [filterAssociation, setFilterAssociation] = useState("all");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedMatter, setSelectedMatter] = useState<any>(null);
  const [editing, setEditing] = useState<any>(null);

  // Form state
  const [form, setForm] = useState({
    association_id: "", unit_id: "", title: "", case_type: "", official_case_name: "",
    case_number: "", current_stage: "intent_to_lien", judge: "", amount_due: "",
    opposing_counsel: "", description: "", category: "general", status: "open", attorney: "",
    has_payment_plan: false, is_bankruptcy: false,
  });

  const fetchData = async () => {
    setLoading(true);
    const [mattersRes, assocRes, unitsRes] = await Promise.all([
      supabase.from("legal_matters").select("*, associations(name), units(unit_number, address, owners(first_name, last_name, status))").order("created_at", { ascending: false }),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
      supabase.from("units").select("id, unit_number, association_id").order("unit_number"),
    ]);
    setMatters(mattersRes.data || []);
    if (assocRes.data) setAssociations(assocRes.data);
    if (unitsRes.data) setUnits(unitsRes.data);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, []);

  const filteredUnits = useMemo(() => {
    if (!form.association_id) return [];
    return units.filter(u => u.association_id === form.association_id);
  }, [form.association_id, units]);

  const openNew = () => {
    setEditing(null);
    setForm({ association_id: "", unit_id: "", title: "", case_type: "", official_case_name: "", case_number: "", current_stage: "intent_to_lien", judge: "", amount_due: "", opposing_counsel: "", description: "", category: "general", status: "open", attorney: "", has_payment_plan: false, is_bankruptcy: false });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!form.association_id || !form.title || !form.case_type || !form.current_stage || !form.description) {
      toast({ title: "Missing fields", description: "Please fill all required fields.", variant: "destructive" });
      return;
    }
    const legalState = normalizeLegalSaveState(form.current_stage, form.status);
    const payload = {
      association_id: form.association_id,
      unit_id: form.unit_id || null,
      title: form.title,
      case_type: toSlug(form.case_type),
      official_case_name: form.official_case_name || null,
      case_number: form.case_number || null,
      current_stage: legalState.current_stage,
      judge: form.judge || null,
      amount_due: form.amount_due ? parseFloat(form.amount_due) : 0,
      opposing_counsel: form.opposing_counsel || null,
      description: form.description,
      category: form.category,
      status: legalState.status,
      attorney: form.attorney || null,
      has_payment_plan: form.has_payment_plan,
      is_bankruptcy: form.is_bankruptcy,
      created_by: user?.id,
    };

    if (editing) {
      const { error } = await supabase.from("legal_matters").update(payload).eq("id", editing.id);
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); return; }
      toast({ title: "Updated" });
    } else {
      const { error } = await supabase.from("legal_matters").insert(payload);
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); return; }
      toast({ title: "Legal case created" });
    }
    setDialogOpen(false);
    fetchData();
  };

  const filtered = matters.filter((m) => {
    const q = search.toLowerCase();
    const ownerNames = getMatterOwnerNames(m);
    const matchesSearch = m.title.toLowerCase().includes(q) ||
      (m.case_number || "").toLowerCase().includes(q) ||
      (m.units?.unit_number || "").toLowerCase().includes(q) ||
      (m.units?.address || "").toLowerCase().includes(q) ||
      ownerNames.some((name) => name.toLowerCase().includes(q));
    const matchesAssoc = filterAssociation === "all" || m.association_id === filterAssociation;
    return matchesSearch && matchesAssoc && !isArchivedLegalMatter(m);
  });

  const handleEdit = (matter: any) => {
    setEditing(matter);
    setForm({
      association_id: matter.association_id || "",
      unit_id: matter.unit_id || "",
      title: matter.title || "",
      case_type: matter.case_type ? fromSlug(matter.case_type) : "",
      official_case_name: matter.official_case_name || "",
      case_number: matter.case_number || "",
      current_stage: matter.current_stage || "intent_to_lien",
      judge: matter.judge || "",
      amount_due: matter.amount_due ? String(matter.amount_due) : "",
      opposing_counsel: matter.opposing_counsel || "",
      description: matter.description || "",
      category: matter.category || "general",
      status: matter.status || "open",
      attorney: matter.attorney || "",
      has_payment_plan: !!matter.has_payment_plan,
      is_bankruptcy: !!matter.is_bankruptcy,
    });
    setSelectedMatter(null);
    setDialogOpen(true);
  };

  const handleDelete = async (matter: any) => {
    const confirmed = window.confirm(`Delete legal matter "${matter.title}"? This cannot be undone.`);
    if (!confirmed) return;
    const { error } = await supabase.from("legal_matters").delete().eq("id", matter.id);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Deleted", description: "Legal matter has been removed." });
      setSelectedMatter(null);
      fetchData();
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Scale className="h-6 w-6 text-primary" /> Legal Matters
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Manage and track legal cases and attorney correspondence.</p>
        </div>
        <div className="flex gap-2">
          <RecordImportButton
            title="Import Legal Cases"
            description="Upload a CSV or Excel file with legal matter records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "case_number", label: "Case Number" },
              { key: "category", label: "Category" },
              { key: "status", label: "Status" },
              { key: "description", label: "Description" },
              { key: "attorney", label: "Attorney" },
            ]}
            onImport={async (rows) => {
              const assocId = associations[0]?.id;
              if (!assocId) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                title: r.title || "Untitled",
                case_number: r.case_number || null,
                category: r.category || "Other",
                status: r.status || "open",
                description: r.description || null,
                attorney: r.attorney || null,
                association_id: assocId,
              }));
              const { error } = await supabase.from("legal_matters").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} legal cases` });
              fetchData();
            }}
            templateFileName="legal_matters_template.xlsx"
          />
          <Button variant="outline" size="sm" onClick={() => {
            import("@/lib/legalMattersPdfExport").then(({ exportLegalMattersPdf }) => {
              exportLegalMattersPdf(filtered.map((m: any) => ({
                title: m.title,
                caseNumber: m.case_number || "",
                association: m.associations?.name || "—",
                unit: m.units?.unit_number || "",
                stage: fromSlug(m.current_stage || ""),
                caseType: fromSlug(m.case_type || ""),
                amountDue: Number(m.amount_due || 0),
                attorney: m.attorney || "",
                status: fromSlug(m.status || ""),
                openedDate: m.opened_date || m.created_at,
              })));
            });
          }}>
            <FileDown className="h-4 w-4 mr-2" /> Export PDF
          </Button>
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> Add Legal Case</Button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex items-center gap-2 text-sm text-muted-foreground font-medium">FILTER BY CLIENT</div>
        <Select value={filterAssociation} onValueChange={setFilterAssociation}>
          <SelectTrigger className="w-48"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Associations</SelectItem>
            {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
          </SelectContent>
        </Select>
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search cases..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
      </div>

      {/* Cases list as cards */}
      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">
          <Scale className="mx-auto h-12 w-12 mb-4 opacity-50" />
          <p>No legal matters found.</p>
        </CardContent></Card>
      ) : (
        <div className="space-y-3">
          {filtered.map((m) => (
            <Card key={m.id} className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setSelectedMatter(m)}>
              <CardContent className="p-4">
                {(() => {
                  const ownerNames = getMatterOwnerNames(m);
                  return (
                <div className="flex items-start justify-between">
                  <div className="space-y-1.5 flex-1">
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold text-base">{m.title}</h3>
                      <Badge className={stageColors[m.current_stage] || "bg-muted text-muted-foreground"}>
                        {fromSlug(m.current_stage || m.status)}
                      </Badge>
                      {m.case_type && (
                        <Badge variant="outline" className="text-xs">{fromSlug(m.case_type)}</Badge>
                      )}
                      {m.has_payment_plan && <Badge variant="secondary" className="text-xs">Payment Plan</Badge>}
                      {m.is_bankruptcy && <Badge variant="destructive" className="text-xs">Bankruptcy</Badge>}
                    </div>
                    <p className="text-sm text-muted-foreground">{m.associations?.name || "—"}</p>
                    {ownerNames.length > 0 && (
                      <p className="text-sm text-foreground">{ownerNames.join(" & ")}</p>
                    )}
                    <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground mt-2">
                      {m.units?.unit_number && (
                        <span className="flex items-center gap-1"><MapPin className="h-3.5 w-3.5" /> {m.units.unit_number}</span>
                      )}
                      {!m.units?.unit_number && (
                        <span className="flex items-center gap-1"><MapPin className="h-3.5 w-3.5" /> No address specified</span>
                      )}
                      {m.current_stage && (
                        <span className="flex items-center gap-1"><Building2 className="h-3.5 w-3.5" /> {fromSlug(m.current_stage)}</span>
                      )}
                      <span className="flex items-center gap-1"><DollarSign className="h-3.5 w-3.5" /> ${Number(m.amount_due || 0).toLocaleString(undefined, { minimumFractionDigits: 2 })} due</span>
                      <span className="flex items-center gap-1"><Calendar className="h-3.5 w-3.5" /> Opened {m.opened_date ? format(new Date(m.opened_date), "MMM d, yyyy") : "N/A"}</span>
                    </div>
                  </div>
                  <div className="flex gap-1">
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => { e.stopPropagation(); handleEdit(m); }}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={(e) => { e.stopPropagation(); handleDelete(m); }}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
                  );
                })()}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Legal Case" : "Create Legal Case"}</DialogTitle>
            <DialogDescription>Record a new legal matter case and link it to a specific property.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 mt-2">
            <div className="space-y-2">
              <Label>Association *</Label>
              <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v, unit_id: "" })}>
                <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
                <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Property *</Label>
              <Select value={form.unit_id} onValueChange={(v) => setForm({ ...form, unit_id: v })} disabled={!form.association_id}>
                <SelectTrigger><SelectValue placeholder="Search and select property..." /></SelectTrigger>
                <SelectContent>{filteredUnits.map(u => <SelectItem key={u.id} value={u.id}>{u.unit_number}</SelectItem>)}</SelectContent>
              </Select>
              {!form.association_id && <p className="text-xs text-muted-foreground">Select an association first to view properties.</p>}
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Case Title *</Label><Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="e.g., Pending Litigation vs Smith" /></div>
              <div className="space-y-2">
                <Label>Case Type *</Label>
                <Select value={form.case_type} onValueChange={(v) => setForm({ ...form, case_type: v })}>
                  <SelectTrigger><SelectValue placeholder="Select Case Type" /></SelectTrigger>
                  <SelectContent>
                    {CASE_TYPES.map(t => <SelectItem key={t} value={t}>{t}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Official Case Name</Label><Input value={form.official_case_name} onChange={(e) => setForm({ ...form, official_case_name: e.target.value })} placeholder="HOA vs Smith" /></div>
              <div className="space-y-2"><Label>Case / Docket Number</Label><Input value={form.case_number} onChange={(e) => setForm({ ...form, case_number: e.target.value })} placeholder="12-3456-CA" /></div>
            </div>
            <div className="grid grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label>Current Stage *</Label>
                <Select value={form.current_stage} onValueChange={(v) => setForm({ ...form, current_stage: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {STAGES.map(s => <SelectItem key={toSlug(s)} value={toSlug(s)}>{s}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2"><Label>Judge</Label><Input value={form.judge} onChange={(e) => setForm({ ...form, judge: e.target.value })} placeholder="Hon. Jane Doe" /></div>
              <div className="space-y-2"><Label>Amount Due ($)</Label><Input type="number" step="0.01" value={form.amount_due} onChange={(e) => setForm({ ...form, amount_due: e.target.value })} placeholder="0.00" /></div>
            </div>
            <div className="space-y-2"><Label>Opposing Counsel</Label><Input value={form.opposing_counsel} onChange={(e) => setForm({ ...form, opposing_counsel: e.target.value })} placeholder="Attorney name or firm" /></div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 rounded-md border border-border p-3">
              <div className="flex items-center justify-between gap-3">
                <Label className="text-sm font-medium">Payment Plan</Label>
                <Switch checked={form.has_payment_plan} onCheckedChange={(checked) => setForm({ ...form, has_payment_plan: checked })} />
              </div>
              <div className="flex items-center justify-between gap-3">
                <Label className="text-sm font-medium">Bankruptcy</Label>
                <Switch checked={form.is_bankruptcy} onCheckedChange={(checked) => setForm({ ...form, is_bankruptcy: checked })} />
              </div>
            </div>
            <div className="space-y-2"><Label>Matter Details *</Label><Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Detailed description of the legal matter, history, and next steps..." className="min-h-[100px]" /></div>
          </div>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave}>Save Legal Case</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail Dialog */}
      <Dialog open={!!selectedMatter} onOpenChange={(open) => !open && setSelectedMatter(null)}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><Scale className="w-5 h-5" /> Legal Case Details</DialogTitle>
          </DialogHeader>
          {selectedMatter && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div><p className="text-sm text-muted-foreground">Case Title</p><p className="font-medium">{selectedMatter.title}</p></div>
                <div><p className="text-sm text-muted-foreground">Stage</p><Badge className={stageColors[selectedMatter.current_stage] || "bg-muted text-muted-foreground"}>{fromSlug(selectedMatter.current_stage || selectedMatter.status)}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Association</p><p className="font-medium">{selectedMatter.associations?.name || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Property</p><p className="font-medium">{selectedMatter.units?.unit_number || "—"}</p></div>
                <div className="col-span-2"><p className="text-sm text-muted-foreground">Owners</p><p className="font-medium">{getMatterOwnerNames(selectedMatter).join(" & ") || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Case Type</p><p className="font-medium">{selectedMatter.case_type ? fromSlug(selectedMatter.case_type) : "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Case #</p><p className="font-medium">{selectedMatter.case_number || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Judge</p><p className="font-medium">{selectedMatter.judge || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Amount Due</p><p className="font-medium">${Number(selectedMatter.amount_due || 0).toLocaleString(undefined, { minimumFractionDigits: 2 })}</p></div>
                <div><p className="text-sm text-muted-foreground">Opposing Counsel</p><p className="font-medium">{selectedMatter.opposing_counsel || "—"}</p></div>
                <div><p className="text-sm text-muted-foreground">Opened</p><p className="font-medium">{selectedMatter.opened_date ? format(new Date(selectedMatter.opened_date), "MMMM d, yyyy") : "—"}</p></div>
              </div>
              {(selectedMatter.has_payment_plan || selectedMatter.is_bankruptcy) && (
                <div className="flex flex-wrap gap-2">
                  {selectedMatter.has_payment_plan && <Badge variant="secondary">Payment Plan</Badge>}
                  {selectedMatter.is_bankruptcy && <Badge variant="destructive">Bankruptcy</Badge>}
                </div>
              )}
              {selectedMatter.official_case_name && (
                <div><p className="text-sm text-muted-foreground">Official Case Name</p><p className="font-medium">{selectedMatter.official_case_name}</p></div>
              )}
              {selectedMatter.description && (
                <div><p className="text-sm text-muted-foreground">Matter Details</p><p className="bg-muted p-3 rounded-md mt-1 border whitespace-pre-wrap">{selectedMatter.description}</p></div>
              )}
              {selectedMatter.collection_id && (
                <Badge variant="outline" className="text-xs">Linked to Collection</Badge>
              )}
              <VotingAndComments entityType="legal_matter" entityId={selectedMatter.id} showVoting={false} />
              <Separator />
              <div className="flex justify-end gap-2">
                <Button variant="outline" className="gap-2" onClick={() => handleEdit(selectedMatter)}>
                  <Pencil className="h-4 w-4" /> Edit
                </Button>
                <Button variant="destructive" className="gap-2" onClick={() => handleDelete(selectedMatter)}>
                  <Trash2 className="h-4 w-4" /> Delete
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
