import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Edit, Trash2, BookOpen, Loader2, ExternalLink, FileText, FilterX } from "lucide-react";
import type { Tables } from "@/integrations/supabase/types";

type Resource = {
  id: string; association_id: string; title: string; category: string;
  resource_type: string; url: string | null; file_url: string | null;
  description: string | null; sort_order: number | null; is_active: boolean;
  created_at: string; associations?: { name: string } | null;
};

const CATEGORIES = ["General", "Legal", "Finance", "Onboarding", "Governance", "Insurance", "Maintenance"];
const emptyForm = { title: "", category: "General", resource_type: "link", url: "", file_url: "", description: "", sort_order: 0, is_active: true, association_ids: [] as string[] };

export default function ManageBoardResourcesPage() {
  const { toast } = useToast();
  const [resources, setResources] = useState<Resource[]>([]);
  const [associations, setAssociations] = useState<Tables<"associations">[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedAssoc, setSelectedAssoc] = useState("all");

  const [formOpen, setFormOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Resource | null>(null);

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

  const fetchData = async () => {
    setLoading(true);
    const [rRes, aRes] = await Promise.all([
      supabase.from("board_resources").select("*, associations(name)").order("category").order("sort_order"),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
    ]);
    if (rRes.data) setResources(rRes.data as Resource[]);
    if (aRes.data) setAssociations(aRes.data as Tables<"associations">[]);
    setLoading(false);
  };

  const filtered = resources.filter(r => selectedAssoc === "all" || r.association_id === selectedAssoc);

  const openAdd = () => { setEditingId(null); setForm({ ...emptyForm, association_ids: [] }); setFormOpen(true); };
  const openEdit = (r: Resource) => {
    setEditingId(r.id);
    setForm({
      title: r.title, category: r.category, resource_type: r.resource_type,
      url: r.url || "", file_url: r.file_url || "", description: r.description || "",
      sort_order: r.sort_order ?? 0, is_active: r.is_active, association_ids: [r.association_id],
    });
    setFormOpen(true);
  };

  const allSelected = form.association_ids.length === associations.length && associations.length > 0;

  const toggleAll = () => {
    if (allSelected) {
      setForm({ ...form, association_ids: [] });
    } else {
      setForm({ ...form, association_ids: associations.map(a => a.id) });
    }
  };

  const toggleAssoc = (id: string) => {
    setForm(prev => ({
      ...prev,
      association_ids: prev.association_ids.includes(id)
        ? prev.association_ids.filter(x => x !== id)
        : [...prev.association_ids, id],
    }));
  };

  const handleSave = async () => {
    if (!form.title || form.association_ids.length === 0) {
      toast({ variant: "destructive", title: "Title and at least one association are required" }); return;
    }
    setSaving(true);
    const base = {
      title: form.title, category: form.category,
      resource_type: form.resource_type, url: form.url || null, file_url: form.file_url || null,
      description: form.description || null, sort_order: form.sort_order, is_active: form.is_active,
    };

    if (editingId) {
      const { error } = await supabase.from("board_resources").update({ ...base, association_id: form.association_ids[0] }).eq("id", editingId);
      if (error) toast({ variant: "destructive", title: "Error", description: error.message });
      else { toast({ title: "Resource updated" }); setFormOpen(false); fetchData(); }
    } else {
      const rows = form.association_ids.map(aid => ({ ...base, association_id: aid }));
      const { error } = await supabase.from("board_resources").insert(rows);
      if (error) toast({ variant: "destructive", title: "Error", description: error.message });
      else { toast({ title: `Resource added to ${rows.length} association(s)` }); setFormOpen(false); fetchData(); }
    }
    setSaving(false);
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    const { error } = await supabase.from("board_resources").delete().eq("id", deleteTarget.id);
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else { toast({ title: "Resource deleted" }); fetchData(); }
    setDeleteOpen(false); setDeleteTarget(null);
  };

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2"><BookOpen className="h-6 w-6 text-primary" /> Manage Board Resources</h1>
          <p className="text-sm text-muted-foreground">Add links, documents, and reading materials for board members.</p>
        </div>
        <Button onClick={openAdd} className="gap-2"><Plus className="h-4 w-4" /> Add Resource</Button>
      </div>

      <Card>
        <CardHeader className="flex flex-col sm:flex-row gap-4 justify-between bg-muted/50 border-b">
          <CardTitle className="text-lg">Resources</CardTitle>
          <div className="flex items-center gap-2">
            <Select value={selectedAssoc} onValueChange={setSelectedAssoc}>
              <SelectTrigger className="w-[200px]"><SelectValue placeholder="Filter by Association" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Associations</SelectItem>
                {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
              </SelectContent>
            </Select>
            {selectedAssoc !== "all" && <Button variant="ghost" size="icon" onClick={() => setSelectedAssoc("all")}><FilterX className="h-4 w-4" /></Button>}
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Association</TableHead>
                <TableHead>Active</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow><TableCell colSpan={6} className="text-center py-8"><Loader2 className="h-6 w-6 animate-spin mx-auto text-primary" /></TableCell></TableRow>
              ) : filtered.length === 0 ? (
                <TableRow><TableCell colSpan={6} className="text-center py-8 text-muted-foreground">No resources found.</TableCell></TableRow>
              ) : filtered.map(r => (
                <TableRow key={r.id}>
                  <TableCell className="font-medium flex items-center gap-2">
                    {r.resource_type === "document" ? <FileText className="h-4 w-4 text-muted-foreground" /> : <ExternalLink className="h-4 w-4 text-muted-foreground" />}
                    {r.title}
                  </TableCell>
                  <TableCell><Badge variant="outline">{r.category}</Badge></TableCell>
                  <TableCell className="capitalize text-sm text-muted-foreground">{r.resource_type}</TableCell>
                  <TableCell className="text-sm">{r.associations?.name || "—"}</TableCell>
                  <TableCell>
                    {r.is_active
                      ? <Badge className="bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/10 border-emerald-200">Active</Badge>
                      : <Badge variant="secondary">Inactive</Badge>}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(r)}><Edit className="h-4 w-4" /></Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={() => { setDeleteTarget(r); setDeleteOpen(true); }}><Trash2 className="h-4 w-4" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Add/Edit Dialog */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader><DialogTitle>{editingId ? "Edit" : "Add"} Resource</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Association(s) *</Label>
              {editingId ? (
                <Select value={form.association_ids[0] || ""} onValueChange={v => setForm({ ...form, association_ids: [v] })}>
                  <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                  <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
                </Select>
              ) : (
                <div className="border rounded-md p-3 space-y-2 max-h-48 overflow-y-auto">
                  <div className="flex items-center gap-2 pb-2 border-b">
                    <Checkbox
                      id="all-assoc"
                      checked={allSelected}
                      onCheckedChange={toggleAll}
                    />
                    <label htmlFor="all-assoc" className="text-sm font-medium cursor-pointer">Select All Associations</label>
                  </div>
                  {associations.map(a => (
                    <div key={a.id} className="flex items-center gap-2">
                      <Checkbox
                        id={`assoc-${a.id}`}
                        checked={form.association_ids.includes(a.id)}
                        onCheckedChange={() => toggleAssoc(a.id)}
                      />
                      <label htmlFor={`assoc-${a.id}`} className="text-sm cursor-pointer">{a.name}</label>
                    </div>
                  ))}
                </div>
              )}
              {!editingId && form.association_ids.length > 0 && (
                <p className="text-xs text-muted-foreground">{form.association_ids.length} association(s) selected</p>
              )}
            </div>
            <div className="space-y-2"><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 className="space-y-2">
                <Label>Category</Label>
                <Select value={form.category} onValueChange={v => setForm({ ...form, category: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>{CATEGORIES.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Type</Label>
                <Select value={form.resource_type} onValueChange={v => setForm({ ...form, resource_type: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="link">External Link</SelectItem>
                    <SelectItem value="document">Document</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            {form.resource_type === "link" ? (
              <div className="space-y-2"><Label>URL</Label><Input type="url" placeholder="https://..." value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} /></div>
            ) : (
              <div className="space-y-2"><Label>File URL</Label><Input placeholder="Paste document URL" value={form.file_url} onChange={e => setForm({ ...form, file_url: e.target.value })} /></div>
            )}
            <div className="space-y-2"><Label>Description</Label><Textarea rows={2} value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} /></div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Sort Order</Label><Input type="number" value={form.sort_order} onChange={e => setForm({ ...form, sort_order: Number(e.target.value) })} /></div>
              <div className="flex items-center gap-3 pt-6">
                <Switch checked={form.is_active} onCheckedChange={v => setForm({ ...form, is_active: v })} />
                <Label>Active</Label>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormOpen(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving} className="gap-2">
              {saving && <Loader2 className="h-4 w-4 animate-spin" />} {editingId ? "Update" : "Add"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle className="text-destructive">Delete Resource</DialogTitle></DialogHeader>
          <p className="text-sm text-muted-foreground">Are you sure you want to delete "{deleteTarget?.title}"?</p>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteOpen(false)}>Cancel</Button>
            <Button variant="destructive" onClick={handleDelete}>Delete</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}