import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Home, 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
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> = { open: "bg-blue-100 text-blue-700", "in-progress": "bg-amber-100 text-amber-700", resolved: "bg-emerald-100 text-emerald-700", closed: "bg-muted text-muted-foreground" };

export default function HomeownerRequestsPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { toast } = useToast();
  const [requests, setRequests] = 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({ title: "", description: "", category: "general", status: "open", priority: "medium" });

  const isBoardView = !!boardAssociationIds?.length;
  const fetchData = async () => { setLoading(true); let query = supabase.from("homeowner_requests").select("*, associations(name), owners(first_name, last_name)").order("created_at", { ascending: false }); if (isBoardView) query = query.in("association_id", boardAssociationIds!); const { data } = await query; setRequests(data || []); setLoading(false); };
  useEffect(() => { fetchData(); }, []);
  const openNew = () => { setEditing(null); setForm({ title: "", description: "", category: "general", status: "open", priority: "medium" }); setDialogOpen(true); };
  const openEdit = (r: any) => { setEditing(r); setForm({ title: r.title, description: r.description || "", category: r.category || "general", status: r.status, priority: r.priority || "medium" }); setDialogOpen(true); };
  const handleSave = async () => {
    if (editing) { await supabase.from("homeowner_requests").update(form).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("homeowner_requests").insert({ ...form, association_id: a[0].id }); toast({ title: "Request created" }); }
    setDialogOpen(false); fetchData();
  };
  const handleDelete = async (id: string) => { await supabase.from("homeowner_requests").delete().eq("id", id); toast({ title: "Deleted" }); fetchData(); };
  const filtered = requests.filter((r) => r.title.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"><Home className="h-6 w-6 text-primary" /> Homeowner Requests</h1><p className="text-sm text-muted-foreground mt-1">Track and manage homeowner requests.</p></div>
        {!isBoardView && <div className="flex gap-2">
          <RecordImportButton
            title="Import Homeowner Requests"
            description="Upload a CSV or Excel file with request records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "description", label: "Description" },
              { key: "category", label: "Category" },
              { key: "priority", label: "Priority" },
              { key: "status", label: "Status" },
            ]}
            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 => ({
                title: r.title || "Untitled",
                description: r.description || null,
                category: r.category || "general",
                priority: r.priority || "medium",
                status: r.status || "open",
                association_id: a[0].id,
              }));
              const { error } = await supabase.from("homeowner_requests").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} requests` });
              fetchData();
            }}
            templateFileName="requests_template.xlsx"
          />
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> New Request</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 requests found.</CardContent></Card> : (
        <Card><Table><TableHeader><TableRow><TableHead>Title</TableHead><TableHead>Owner</TableHead><TableHead>Category</TableHead><TableHead>Priority</TableHead><TableHead>Status</TableHead><TableHead className="w-12" /></TableRow></TableHeader><TableBody>
          {filtered.map((r) => (<TableRow key={r.id}><TableCell className="font-medium">{r.title}</TableCell><TableCell>{r.owners ? `${r.owners.first_name} ${r.owners.last_name}` : "—"}</TableCell><TableCell className="capitalize">{r.category}</TableCell><TableCell className="capitalize">{r.priority}</TableCell><TableCell><Badge className={statusColors[r.status] || "bg-muted text-muted-foreground"}>{r.status}</Badge></TableCell>{!isBoardView && <TableCell>
            <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(r)}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem><DropdownMenuItem className="text-destructive" onClick={() => handleDelete(r.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"} Request</DialogTitle></DialogHeader>
        <div className="space-y-4">
          <div><Label>Title</Label><Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} /></div>
          <div className="grid grid-cols-2 gap-4"><div><Label>Category</Label><Select value={form.category} onValueChange={(v) => setForm({ ...form, category: v })}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="general">General</SelectItem><SelectItem value="maintenance">Maintenance</SelectItem><SelectItem value="complaint">Complaint</SelectItem><SelectItem value="architectural">Architectural</SelectItem></SelectContent></Select></div><div><Label>Priority</Label><Select value={form.priority} onValueChange={(v) => setForm({ ...form, priority: v })}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="low">Low</SelectItem><SelectItem value="medium">Medium</SelectItem><SelectItem value="high">High</SelectItem></SelectContent></Select></div></div>
          <div><Label>Status</Label><Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent><SelectItem value="open">Open</SelectItem><SelectItem value="in-progress">In Progress</SelectItem><SelectItem value="resolved">Resolved</SelectItem><SelectItem value="closed">Closed</SelectItem></SelectContent></Select></div>
          <div><Label>Description</Label><Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></div>
        </div><DialogFooter><Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button></DialogFooter></DialogContent></Dialog>
    </div>
  );
}
