import { useState, useEffect, useCallback } 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 { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Plus, Trash2, Edit, Loader2, GripVertical, ChevronRight, FolderTree } from "lucide-react";

interface Category {
  id: string;
  name: string;
  description: string | null;
  color: string | null;
  is_active: boolean;
  sort_order: number;
}

interface Subcategory {
  id: string;
  category_id: string;
  name: string;
  description: string | null;
  is_active: boolean;
  sort_order: number;
}

export default function ExpenseSettingsPanel() {
  const { toast } = useToast();
  const [categories, setCategories] = useState<Category[]>([]);
  const [subcategories, setSubcategories] = useState<Subcategory[]>([]);
  const [loading, setLoading] = useState(true);

  // Category dialog
  const [catDialogOpen, setCatDialogOpen] = useState(false);
  const [editingCat, setEditingCat] = useState<Category | null>(null);
  const [catForm, setCatForm] = useState({ name: "", description: "", color: "#6366f1" });
  const [catSaving, setCatSaving] = useState(false);

  // Subcategory dialog
  const [subDialogOpen, setSubDialogOpen] = useState(false);
  const [editingSub, setEditingSub] = useState<Subcategory | null>(null);
  const [subForm, setSubForm] = useState({ name: "", description: "", category_id: "" });
  const [subSaving, setSubSaving] = useState(false);

  // Delete
  const [deleteTarget, setDeleteTarget] = useState<{ type: "category" | "subcategory"; id: string; name: string } | null>(null);

  const fetchAll = useCallback(async () => {
    setLoading(true);
    const [catRes, subRes] = await Promise.all([
      supabase.from("expense_categories").select("*").order("sort_order").order("name"),
      supabase.from("expense_subcategories").select("*").order("sort_order").order("name"),
    ]);
    if (catRes.data) setCategories(catRes.data as Category[]);
    if (subRes.data) setSubcategories(subRes.data as Subcategory[]);
    setLoading(false);
  }, []);

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

  // Category CRUD
  const openAddCat = () => {
    setEditingCat(null);
    setCatForm({ name: "", description: "", color: "#6366f1" });
    setCatDialogOpen(true);
  };

  const openEditCat = (cat: Category) => {
    setEditingCat(cat);
    setCatForm({ name: cat.name, description: cat.description || "", color: cat.color || "#6366f1" });
    setCatDialogOpen(true);
  };

  const saveCat = async () => {
    if (!catForm.name.trim()) {
      toast({ variant: "destructive", title: "Name is required" }); return;
    }
    setCatSaving(true);
    const payload = { name: catForm.name.trim(), description: catForm.description || null, color: catForm.color || null };

    if (editingCat) {
      const { error } = await supabase.from("expense_categories").update({ ...payload, updated_at: new Date().toISOString() }).eq("id", editingCat.id);
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); setCatSaving(false); return; }
      toast({ title: "Category updated" });
    } else {
      const maxOrder = categories.length > 0 ? Math.max(...categories.map(c => c.sort_order)) + 1 : 0;
      const { error } = await supabase.from("expense_categories").insert({ ...payload, sort_order: maxOrder });
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); setCatSaving(false); return; }
      toast({ title: "Category created" });
    }
    setCatDialogOpen(false);
    setCatSaving(false);
    fetchAll();
  };

  const toggleCatActive = async (cat: Category) => {
    await supabase.from("expense_categories").update({ is_active: !cat.is_active, updated_at: new Date().toISOString() }).eq("id", cat.id);
    fetchAll();
  };

  // Subcategory CRUD
  const openAddSub = (categoryId: string) => {
    setEditingSub(null);
    setSubForm({ name: "", description: "", category_id: categoryId });
    setSubDialogOpen(true);
  };

  const openEditSub = (sub: Subcategory) => {
    setEditingSub(sub);
    setSubForm({ name: sub.name, description: sub.description || "", category_id: sub.category_id });
    setSubDialogOpen(true);
  };

  const saveSub = async () => {
    if (!subForm.name.trim()) {
      toast({ variant: "destructive", title: "Name is required" }); return;
    }
    setSubSaving(true);
    const payload = { name: subForm.name.trim(), description: subForm.description || null, category_id: subForm.category_id };

    if (editingSub) {
      const { error } = await supabase.from("expense_subcategories").update({ ...payload, updated_at: new Date().toISOString() }).eq("id", editingSub.id);
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); setSubSaving(false); return; }
      toast({ title: "Subcategory updated" });
    } else {
      const catSubs = subcategories.filter(s => s.category_id === subForm.category_id);
      const maxOrder = catSubs.length > 0 ? Math.max(...catSubs.map(s => s.sort_order)) + 1 : 0;
      const { error } = await supabase.from("expense_subcategories").insert({ ...payload, sort_order: maxOrder });
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); setSubSaving(false); return; }
      toast({ title: "Subcategory created" });
    }
    setSubDialogOpen(false);
    setSubSaving(false);
    fetchAll();
  };

  const toggleSubActive = async (sub: Subcategory) => {
    await supabase.from("expense_subcategories").update({ is_active: !sub.is_active, updated_at: new Date().toISOString() }).eq("id", sub.id);
    fetchAll();
  };

  // Delete
  const confirmDelete = async () => {
    if (!deleteTarget) return;
    const table = deleteTarget.type === "category" ? "expense_categories" : "expense_subcategories";
    const { error } = await supabase.from(table).delete().eq("id", deleteTarget.id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      toast({ title: `${deleteTarget.type === "category" ? "Category" : "Subcategory"} deleted` });
    }
    setDeleteTarget(null);
    fetchAll();
  };

  const getSubsForCategory = (catId: string) => subcategories.filter(s => s.category_id === catId);

  if (loading) {
    return <div className="flex items-center justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Expense Categories & Subcategories</h2>
          <p className="text-sm text-muted-foreground">Manage categories used across billable expenses and fee schedules.</p>
        </div>
        <Button onClick={openAddCat} className="gap-2"><Plus className="h-4 w-4" /> Add Category</Button>
      </div>

      {categories.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            <FolderTree className="h-8 w-8 mx-auto mb-2 opacity-50" />
            <p>No categories yet. Click "Add Category" to get started.</p>
          </CardContent>
        </Card>
      ) : (
        <Accordion type="multiple" defaultValue={categories.map(c => c.id)} className="space-y-3">
          {categories.map(cat => {
            const subs = getSubsForCategory(cat.id);
            return (
              <AccordionItem key={cat.id} value={cat.id} className="border rounded-lg bg-card overflow-hidden">
                <AccordionTrigger className="px-4 py-3 hover:no-underline">
                  <div className="flex items-center gap-3 flex-1">
                    <div className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: cat.color || "#6366f1" }} />
                    <span className="font-semibold text-sm">{cat.name}</span>
                    <Badge variant="secondary" className="text-[10px]">{subs.length} sub{subs.length !== 1 ? "s" : ""}</Badge>
                    {!cat.is_active && <Badge variant="outline" className="text-[10px] text-muted-foreground">Inactive</Badge>}
                  </div>
                </AccordionTrigger>
                <AccordionContent className="px-4 pb-4">
                  <div className="flex items-center justify-between mb-3 pt-1">
                    <div className="flex items-center gap-3">
                      <div className="flex items-center gap-2">
                        <Switch checked={cat.is_active} onCheckedChange={() => toggleCatActive(cat)} />
                        <span className="text-xs text-muted-foreground">Active</span>
                      </div>
                      {cat.description && <span className="text-xs text-muted-foreground italic">{cat.description}</span>}
                    </div>
                    <div className="flex gap-1">
                      <Button variant="ghost" size="sm" className="h-7 text-xs gap-1" onClick={() => openAddSub(cat.id)}>
                        <Plus className="h-3 w-3" /> Add Subcategory
                      </Button>
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEditCat(cat)}>
                        <Edit className="h-3.5 w-3.5" />
                      </Button>
                      <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive" onClick={() => setDeleteTarget({ type: "category", id: cat.id, name: cat.name })}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>

                  {subs.length === 0 ? (
                    <div className="text-xs text-muted-foreground py-3 text-center border rounded-md bg-muted/30">
                      No subcategories. Click "+ Add Subcategory" to create one.
                    </div>
                  ) : (
                    <div className="border rounded-md overflow-hidden">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-muted/50">
                            <TableHead className="text-xs h-8">Subcategory</TableHead>
                            <TableHead className="text-xs h-8">Description</TableHead>
                            <TableHead className="text-xs h-8 w-20 text-center">Active</TableHead>
                            <TableHead className="text-xs h-8 w-24 text-right">Actions</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {subs.map(sub => (
                            <TableRow key={sub.id}>
                              <TableCell className="text-sm font-medium py-2">{sub.name}</TableCell>
                              <TableCell className="text-xs text-muted-foreground py-2">{sub.description || "—"}</TableCell>
                              <TableCell className="text-center py-2">
                                <Switch checked={sub.is_active} onCheckedChange={() => toggleSubActive(sub)} />
                              </TableCell>
                              <TableCell className="text-right py-2">
                                <div className="flex justify-end gap-1">
                                  <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEditSub(sub)}>
                                    <Edit className="h-3.5 w-3.5" />
                                  </Button>
                                  <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive" onClick={() => setDeleteTarget({ type: "subcategory", id: sub.id, name: sub.name })}>
                                    <Trash2 className="h-3.5 w-3.5" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </AccordionContent>
              </AccordionItem>
            );
          })}
        </Accordion>
      )}

      {/* Category Dialog */}
      <Dialog open={catDialogOpen} onOpenChange={setCatDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{editingCat ? "Edit Category" : "Add Category"}</DialogTitle>
            <DialogDescription>Define a category for organizing expenses.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label>Name *</Label>
              <Input value={catForm.name} onChange={e => setCatForm(p => ({ ...p, name: e.target.value }))} placeholder="e.g. Maintenance" />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Input value={catForm.description} onChange={e => setCatForm(p => ({ ...p, description: e.target.value }))} placeholder="Optional description" />
            </div>
            <div className="space-y-2">
              <Label>Color</Label>
              <div className="flex items-center gap-3">
                <input type="color" value={catForm.color} onChange={e => setCatForm(p => ({ ...p, color: e.target.value }))} className="w-10 h-10 rounded cursor-pointer border" />
                <span className="text-sm text-muted-foreground">{catForm.color}</span>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCatDialogOpen(false)}>Cancel</Button>
            <Button onClick={saveCat} disabled={catSaving}>
              {catSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {editingCat ? "Update" : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Subcategory Dialog */}
      <Dialog open={subDialogOpen} onOpenChange={setSubDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{editingSub ? "Edit Subcategory" : "Add Subcategory"}</DialogTitle>
            <DialogDescription>
              Under: {categories.find(c => c.id === subForm.category_id)?.name || "—"}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label>Name *</Label>
              <Input value={subForm.name} onChange={e => setSubForm(p => ({ ...p, name: e.target.value }))} placeholder="e.g. Plumbing" />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Input value={subForm.description} onChange={e => setSubForm(p => ({ ...p, description: e.target.value }))} placeholder="Optional description" />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setSubDialogOpen(false)}>Cancel</Button>
            <Button onClick={saveSub} disabled={subSaving}>
              {subSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {editingSub ? "Update" : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <AlertDialog open={!!deleteTarget} onOpenChange={open => { if (!open) setDeleteTarget(null); }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete {deleteTarget?.type === "category" ? "Category" : "Subcategory"}</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete "{deleteTarget?.name}"?
              {deleteTarget?.type === "category" && " This will also delete all its subcategories."}
              {" "}This cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Delete</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
