import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { useAssociationCustomVariables, type AssociationCustomVariable as CustomVariable } from "@/hooks/useAssociationCustomVariables";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Edit2, Trash2, Search, Variable, Copy } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

const CATEGORIES = ["general", "financial", "legal", "contact", "property", "other"];

export default function CustomVariablesManager() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<any[]>([]);
  const [selectedAssocId, setSelectedAssocId] = useState("");
  const { variables, loading, fetchVariables, createVariable, updateVariable, deleteVariable } = useAssociationCustomVariables(selectedAssocId);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<CustomVariable | null>(null);
  const [form, setForm] = useState({ variable_name: "", display_label: "", default_value: "", description: "", category: "general" });
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    supabase.from("associations").select("id, name").eq("status", "active").order("name").then(({ data }) => {
      setAssociations(data || []);
      if (data?.length && !selectedAssocId) setSelectedAssocId(data[0].id);
    });
  }, []);

  const filtered = variables.filter(v =>
    v.variable_name.toLowerCase().includes(search.toLowerCase()) ||
    v.display_label.toLowerCase().includes(search.toLowerCase()) ||
    (v.description || "").toLowerCase().includes(search.toLowerCase())
  );

  const grouped = CATEGORIES.reduce<Record<string, CustomVariable[]>>((acc, cat) => {
    const items = filtered.filter(v => v.category === cat);
    if (items.length > 0) acc[cat] = items;
    return acc;
  }, {});

  const openCreate = () => {
    setEditing(null);
    setForm({ variable_name: "", display_label: "", default_value: "", description: "", category: "general" });
    setDialogOpen(true);
  };

  const openEdit = (v: CustomVariable) => {
    setEditing(v);
    setForm({
      variable_name: v.variable_name,
      display_label: v.display_label,
      default_value: v.default_value || "",
      description: v.description || "",
      category: v.category || "general",
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    console.log("[CustomVariablesManager] handleSave called", { form, selectedAssocId, editing });
    if (!form.variable_name.trim() || !form.display_label.trim()) {
      toast({ title: "Variable name and label are required", variant: "destructive" });
      return;
    }
    if (!selectedAssocId) {
      toast({ title: "Please select an association first", variant: "destructive" });
      return;
    }
    const cleanName = form.variable_name.replace(/[{}]/g, "").replace(/\s+/g, "_").toLowerCase();

    setSaving(true);
    try {
      if (editing) {
        console.log("[CustomVariablesManager] Calling updateVariable...");
        await updateVariable(editing.id, {
          variable_name: cleanName,
          display_label: form.display_label.trim(),
          default_value: form.default_value,
          description: form.description || null,
          category: form.category,
        });
      } else {
        console.log("[CustomVariablesManager] Calling createVariable...", { selectedAssocId, cleanName });
        const result = await createVariable({
          association_id: selectedAssocId,
          variable_name: cleanName,
          display_label: form.display_label.trim(),
          default_value: form.default_value || "",
          description: form.description || null,
          category: form.category || "general",
        });
        console.log("[CustomVariablesManager] createVariable returned:", result);
      }
      setDialogOpen(false);
    } catch (err: any) {
      console.error("[CustomVariablesManager] Save error:", err);
      toast({ title: "Error saving variable", description: err.message, variant: "destructive" });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (v: CustomVariable) => {
    try {
      await deleteVariable(v.id);
    } catch (err: any) {
      toast({ title: "Error", description: err.message, variant: "destructive" });
    }
  };

  const copyTag = (name: string) => {
    navigator.clipboard.writeText(`{{${name}}}`);
    toast({ title: "Copied!", description: `{{${name}}} copied to clipboard` });
  };

  return (
    <div className="p-6 space-y-5 max-w-5xl mx-auto">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-bold text-foreground flex items-center gap-2">
            <Variable className="h-5 w-5 text-primary" /> Custom Variables
          </h2>
          <p className="text-sm text-muted-foreground mt-0.5">
            Create reusable variables for letters, forms, and notices. Use <code className="bg-muted px-1 rounded text-xs font-mono">{"{{variable_name}}"}</code> in your templates.
          </p>
        </div>
        <div className="flex gap-2">
          <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
            <SelectTrigger className="w-[220px] h-9 text-xs">
              <SelectValue placeholder="Select Association" />
            </SelectTrigger>
            <SelectContent>
              {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
            </SelectContent>
          </Select>
          <Button size="sm" className="gap-1.5" onClick={openCreate} disabled={!selectedAssocId}>
            <Plus className="h-4 w-4" /> Add Variable
          </Button>
        </div>
      </div>

      {/* Search */}
      <div className="relative 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 variables..." className="pl-10" value={search} onChange={e => setSearch(e.target.value)} />
      </div>

      {/* Variables Table */}
      {loading ? (
        <div className="space-y-2">{Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-12 w-full" />)}</div>
      ) : !selectedAssocId ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">Select an association to manage its custom variables.</CardContent></Card>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">
          {search ? "No variables match your search." : "No custom variables yet. Click \"Add Variable\" to create one."}
        </CardContent></Card>
      ) : (
        Object.entries(grouped).map(([category, vars]) => (
          <Card key={category} className="border shadow-sm">
            <CardHeader className="py-3 px-4">
              <CardTitle className="text-sm font-semibold capitalize">{category}</CardTitle>
            </CardHeader>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="text-xs">Variable Tag</TableHead>
                  <TableHead className="text-xs">Label</TableHead>
                  <TableHead className="text-xs">Default Value</TableHead>
                  <TableHead className="text-xs">Description</TableHead>
                  <TableHead className="text-xs text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {vars.map(v => (
                  <TableRow key={v.id}>
                    <TableCell>
                      <button onClick={() => copyTag(v.variable_name)} className="flex items-center gap-1.5 group" title="Click to copy">
                        <code className="font-mono text-xs font-semibold text-primary bg-primary/10 px-2 py-0.5 rounded">
                          {`{{${v.variable_name}}}`}
                        </code>
                        <Copy className="h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
                      </button>
                    </TableCell>
                    <TableCell className="text-sm font-medium">{v.display_label}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{v.default_value || "—"}</TableCell>
                    <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate">{v.description || "—"}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-1">
                        <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEdit(v)}>
                          <Edit2 className="h-3.5 w-3.5" />
                        </Button>
                        <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => handleDelete(v)}>
                          <Trash2 className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        ))
      )}

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Variable" : "Create Variable"}</DialogTitle>
            <DialogDescription>
              {editing ? "Update this custom variable." : "Define a new variable to use in your templates."}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Variable Name</Label>
              <Input
                value={form.variable_name}
                onChange={e => setForm({ ...form, variable_name: e.target.value })}
                placeholder="e.g. late_fee_amount"
              />
              <p className="text-xs text-muted-foreground">
                Use in templates as: <code className="bg-muted px-1 rounded font-mono">{`{{${form.variable_name.replace(/[{}]/g, "").replace(/\s+/g, "_").toLowerCase() || "variable_name"}}}`}</code>
              </p>
            </div>
            <div className="space-y-2">
              <Label>Display Label</Label>
              <Input value={form.display_label} onChange={e => setForm({ ...form, display_label: e.target.value })} placeholder="e.g. Late Fee Amount" />
            </div>
            <div className="space-y-2">
              <Label>Default Value</Label>
              <Input value={form.default_value} onChange={e => setForm({ ...form, default_value: e.target.value })} placeholder="e.g. $25.00" />
            </div>
            <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} className="capitalize">{c}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Input value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} placeholder="What this variable represents..." />
            </div>
          </div>
          <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
            <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button type="button" onClick={handleSave} disabled={saving}>
              {saving ? "Saving..." : editing ? "Save Changes" : "Create Variable"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
