import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FileText, Plus, Search, MoreHorizontal, Edit, Trash2 } 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, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";

const statusColors: Record<string, string> = { requested: "bg-amber-100 text-amber-700", "in-progress": "bg-blue-100 text-blue-700", completed: "bg-emerald-100 text-emerald-700", cancelled: "bg-muted text-muted-foreground" };

export default function EstoppelsPage({ boardAssociationIds, viewerRole }: { boardAssociationIds?: string[]; viewerRole?: "board" | "staff" } = {}) {
  const { toast } = useToast();
  const isBoardView = !!boardAssociationIds?.length || viewerRole === "board";
  const [estoppels, setEstoppels] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({ address: "", status: "requested", requestor_name: "", requestor_email: "", fee: "", notes: "" });

  const fetchData = async () => {
    setLoading(true);
    let query = supabase.from("estoppels").select("*, associations(name)").order("created_at", { ascending: false });
    if (isBoardView && boardAssociationIds?.length) query = query.in("association_id", boardAssociationIds);
    const { data } = await query;
    setEstoppels(data || []);
    setLoading(false);
  };
  useEffect(() => { fetchData(); }, []);
  const openNew = () => { setEditing(null); setForm({ address: "", status: "requested", requestor_name: "", requestor_email: "", fee: "", notes: "" }); setDialogOpen(true); };
  const openEdit = (e: any) => { setEditing(e); setForm({ address: e.address || "", status: e.status, requestor_name: e.requestor_name || "", requestor_email: e.requestor_email || "", fee: e.fee?.toString() || "", notes: e.notes || "" }); setDialogOpen(true); };
  const handleSave = async () => {
    const payload = { ...form, fee: form.fee ? parseFloat(form.fee) : null };
    if (editing) { await supabase.from("estoppels").update(payload).eq("id", editing.id); toast({ title: "Updated" }); }
    else { const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1); if (!a?.length) return; await supabase.from("estoppels").insert({ ...payload, association_id: a[0].id }); toast({ title: "Estoppel created" }); }
    setDialogOpen(false); fetchData();
  };
  const handleDelete = async (id: string) => { await supabase.from("estoppels").delete().eq("id", id); toast({ title: "Deleted" }); fetchData(); };
  const filtered = estoppels.filter((e) => (e.address || "").toLowerCase().includes(search.toLowerCase()) || (e.requestor_name || "").toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-6">
      <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"><FileText className="h-6 w-6 text-primary" /> Estoppels</h1><p className="text-sm text-muted-foreground mt-1">Manage estoppel letter requests and processing.</p></div>
        {!isBoardView && <div className="flex gap-2">
          <RecordImportButton
            title="Import Estoppels"
            description="Upload a CSV or Excel file with estoppel records."
            expectedColumns={[
              { key: "address", label: "Address", required: true },
              { key: "requestor_name", label: "Requestor Name" },
              { key: "requestor_email", label: "Requestor Email" },
              { key: "fee", label: "Fee" },
              { key: "status", label: "Status" },
              { key: "notes", label: "Notes" },
            ]}
            onImport={async (rows) => {
              const { data: a } = await supabase.from("associations").select("id").eq("status", "active").limit(1);
              if (!a?.length) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                address: r.address || null,
                requestor_name: r.requestor_name || null,
                requestor_email: r.requestor_email || null,
                fee: r.fee ? parseFloat(r.fee) : null,
                status: r.status || "requested",
                notes: r.notes || null,
                association_id: a[0].id,
              }));
              const { error } = await supabase.from("estoppels").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} estoppels` });
              fetchData();
            }}
            templateFileName="estoppels_template.xlsx"
          />
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> New Estoppel</Button>
        </div>}
      </div>
      <div className="relative max-w-md"><Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /><Input placeholder="Search..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} /></div>
      {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">No estoppels found.</CardContent></Card> : (
        <Card><Table><TableHeader><TableRow><TableHead>Address</TableHead><TableHead>Requestor</TableHead><TableHead>Fee</TableHead><TableHead>Status</TableHead><TableHead>Requested</TableHead><TableHead className="w-12" /></TableRow></TableHeader><TableBody>
          {filtered.map((e) => (<TableRow key={e.id}><TableCell className="font-medium">{e.address || "—"}</TableCell><TableCell>{e.requestor_name || "—"}</TableCell><TableCell>{e.fee ? `$${Number(e.fee).toLocaleString()}` : "—"}</TableCell><TableCell><Badge className={statusColors[e.status] || "bg-muted text-muted-foreground"}>{e.status}</Badge></TableCell><TableCell>{e.requested_date || "—"}</TableCell><TableCell>
            {!isBoardView && <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem onClick={() => openEdit(e)}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem><DropdownMenuItem className="text-destructive" onClick={() => handleDelete(e.id)}><Trash2 className="h-4 w-4 mr-2" /> Delete</DropdownMenuItem></DropdownMenuContent></DropdownMenu>}</TableCell></TableRow>))}</TableBody></Table></Card>
      )}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}><DialogContent><DialogHeader><DialogTitle>{editing ? "Edit" : "New"} Estoppel</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Address</Label><Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} /></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Requestor</Label><Input value={form.requestor_name} onChange={(e) => setForm({ ...form, requestor_name: e.target.value })} /></div><div><Label>Email</Label><Input value={form.requestor_email} onChange={(e) => setForm({ ...form, requestor_email: e.target.value })} /></div></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Fee</Label><Input type="number" value={form.fee} onChange={(e) => setForm({ ...form, fee: e.target.value })} /></div><div><Label>Status</Label><select className="w-full border rounded p-2" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}><option value="requested">Requested</option><option value="in-progress">In Progress</option><option value="completed">Completed</option><option value="cancelled">Cancelled</option></select></div></div>
          <div><Label>Notes</Label><Textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></div>
        </div><DialogFooter><Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button></DialogFooter></DialogContent></Dialog>
    </div>
  );
}
