import { useEffect, useState } from "react";
import { Plus, Pencil, Trash2, Star, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from "@/components/ui/dialog";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import RichEmailEditor from "@/components/email/RichEmailEditor";

export interface EmailSignature {
  id: string;
  user_id: string;
  name: string;
  html: string;
  is_default: boolean;
}

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  onChanged?: (signatures: EmailSignature[]) => void;
}

export default function EmailSignatureManager({ open, onOpenChange, onChanged }: Props) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [list, setList] = useState<EmailSignature[]>([]);
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState<EmailSignature | null>(null);
  const [name, setName] = useState("");
  const [html, setHtml] = useState("");
  const [isDefault, setIsDefault] = useState(false);
  const [saving, setSaving] = useState(false);

  const fetchList = async () => {
    if (!user?.id) return;
    setLoading(true);
    const { data, error } = await supabase
      .from("email_signatures" as any)
      .select("*")
      .eq("user_id", user.id)
      .order("is_default", { ascending: false })
      .order("name");
    setLoading(false);
    if (error) {
      toast({ variant: "destructive", title: "Failed to load signatures", description: error.message });
      return;
    }
    const rows = (data || []) as unknown as EmailSignature[];
    setList(rows);
    onChanged?.(rows);
  };

  useEffect(() => { if (open) fetchList(); }, [open, user?.id]);

  const startNew = () => {
    setEditing({ id: "", user_id: user?.id || "", name: "", html: "", is_default: false });
    setName(""); setHtml(""); setIsDefault(false);
  };

  const startEdit = (s: EmailSignature) => {
    setEditing(s);
    setName(s.name); setHtml(s.html); setIsDefault(s.is_default);
  };

  const cancelEdit = () => setEditing(null);

  const save = async () => {
    if (!user?.id) return;
    if (!name.trim()) {
      toast({ variant: "destructive", title: "Name required" });
      return;
    }
    setSaving(true);
    try {
      if (isDefault) {
        await supabase.from("email_signatures" as any).update({ is_default: false }).eq("user_id", user.id);
      }
      if (editing?.id) {
        const { error } = await supabase
          .from("email_signatures" as any)
          .update({ name, html, is_default: isDefault })
          .eq("id", editing.id);
        if (error) throw error;
      } else {
        const { error } = await supabase
          .from("email_signatures" as any)
          .insert({ user_id: user.id, name, html, is_default: isDefault });
        if (error) throw error;
      }
      toast({ title: "Signature saved" });
      setEditing(null);
      await fetchList();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Save failed", description: err.message });
    } finally {
      setSaving(false);
    }
  };

  const remove = async (id: string) => {
    if (!confirm("Delete this signature?")) return;
    const { error } = await supabase.from("email_signatures" as any).delete().eq("id", id);
    if (error) { toast({ variant: "destructive", title: "Delete failed", description: error.message }); return; }
    toast({ title: "Deleted" });
    fetchList();
  };

  const makeDefault = async (id: string) => {
    if (!user?.id) return;
    await supabase.from("email_signatures" as any).update({ is_default: false }).eq("user_id", user.id);
    const { error } = await supabase.from("email_signatures" as any).update({ is_default: true }).eq("id", id);
    if (error) { toast({ variant: "destructive", title: "Failed", description: error.message }); return; }
    fetchList();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[720px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Email Signatures</DialogTitle>
          <DialogDescription>
            Create reusable HTML signatures. Pick one in the compose window or mark a default to apply automatically.
          </DialogDescription>
        </DialogHeader>

        {!editing ? (
          <div className="space-y-3">
            <div className="flex justify-end">
              <Button onClick={startNew} size="sm"><Plus className="h-4 w-4 mr-2" /> New Signature</Button>
            </div>
            {loading ? (
              <div className="flex justify-center py-8"><Loader2 className="h-5 w-5 animate-spin" /></div>
            ) : list.length === 0 ? (
              <div className="text-center py-10 text-muted-foreground text-sm">No signatures yet.</div>
            ) : (
              <div className="border rounded-md divide-y">
                {list.map((s) => (
                  <div key={s.id} className="flex items-start justify-between p-3 gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-medium truncate">{s.name}</span>
                        {s.is_default && <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">Default</span>}
                      </div>
                      <div
                        className="mt-2 text-xs text-muted-foreground border rounded p-2 bg-muted/30 max-h-24 overflow-hidden"
                        dangerouslySetInnerHTML={{ __html: s.html || "<em>(empty)</em>" }}
                      />
                    </div>
                    <div className="flex flex-col gap-1">
                      {!s.is_default && (
                        <Button variant="ghost" size="icon" title="Make default" onClick={() => makeDefault(s.id)}>
                          <Star className="h-4 w-4" />
                        </Button>
                      )}
                      <Button variant="ghost" size="icon" onClick={() => startEdit(s)}><Pencil className="h-4 w-4" /></Button>
                      <Button variant="ghost" size="icon" className="text-destructive" onClick={() => remove(s.id)}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : (
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Friendly, Formal, Board Chair" />
            </div>
            <div className="space-y-2">
              <Label>Signature (HTML)</Label>
              <RichEmailEditor value={html} onChange={setHtml} placeholder="Best regards, Jane Doe…" minHeight={200} />
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input type="checkbox" checked={isDefault} onChange={(e) => setIsDefault(e.target.checked)} />
              Use as my default signature
            </label>
            <DialogFooter>
              <Button variant="outline" onClick={cancelEdit}>Cancel</Button>
              <Button onClick={save} disabled={saving}>
                {saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />} Save Signature
              </Button>
            </DialogFooter>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}