import { useState, useEffect } from "react";
import { FileCode, Plus, Pencil, Trash2, Send, RefreshCw } from "lucide-react";
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import NotifyOwnersDialog from "@/components/NotifyOwnersDialog";
import { NotifyOwnersProvider } from "@/contexts/NotifyOwnersContext";

function EmailTemplatesPageContent() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [templates, setTemplates] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [showDialog, setShowDialog] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: "", description: "", subject: "", body_html: "" });

  // State for "Use" template → open compose dialog
  const [showCompose, setShowCompose] = useState(false);
  const [composeTemplate, setComposeTemplate] = useState<any>(null);

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

  const fetchTemplates = async () => {
    setLoading(true);
    const { data } = await supabase.from("email_templates").select("*").order("created_at", { ascending: false });
    setTemplates(data || []);
    setLoading(false);
  };

  const openNew = () => { setEditId(null); setForm({ name: "", description: "", subject: "", body_html: "" }); setShowDialog(true); };
  const openEdit = (t: any) => { setEditId(t.id); setForm({ name: t.name, description: t.description || "", subject: t.subject || "", body_html: t.body_html || "" }); setShowDialog(true); };

  const handleSave = async () => {
    if (!form.name.trim()) { toast({ variant: "destructive", title: "Error", description: "Template name is required." }); return; }
    const payload = { ...form, created_by: user?.id };
    if (editId) {
      await supabase.from("email_templates").update(payload).eq("id", editId);
    } else {
      await supabase.from("email_templates").insert(payload);
    }
    toast({ title: "Saved" }); setShowDialog(false); fetchTemplates();
  };

  const handleDelete = async (id: string) => {
    await supabase.from("email_templates").delete().eq("id", id);
    toast({ title: "Deleted" }); fetchTemplates();
  };

  const handleUseTemplate = (t: any) => {
    setComposeTemplate(t);
    setShowCompose(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <FileCode className="h-7 w-7 text-primary" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">Template Library</h1>
            <p className="text-sm text-muted-foreground">Manage reusable email layouts and content.</p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon" onClick={fetchTemplates}><RefreshCw className="h-4 w-4" /></Button>
          <Button onClick={openNew}><Plus className="h-4 w-4 mr-2" /> Create Template</Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {templates.map((t) => (
          <Card key={t.id} className="flex flex-col">
            <CardHeader className="pb-2">
              <CardTitle className="text-base truncate">{t.name}</CardTitle>
              <CardDescription className="text-xs truncate">{t.description || "No description provided."}</CardDescription>
            </CardHeader>
            <CardContent className="flex-1">
              <div className="h-28 bg-muted rounded-md border flex items-center justify-center overflow-hidden p-3">
                <div className="text-xs text-muted-foreground line-clamp-4 font-mono" dangerouslySetInnerHTML={{ __html: t.body_html || t.subject || "Empty template" }} />
              </div>
            </CardContent>
            <div className="flex items-center justify-between p-4 pt-0">
              <div className="flex gap-1">
                <Button variant="ghost" size="icon" onClick={() => openEdit(t)}><Pencil className="h-4 w-4" /></Button>
                <Button variant="ghost" size="icon" className="text-destructive" onClick={() => handleDelete(t.id)}><Trash2 className="h-4 w-4" /></Button>
              </div>
              <Button size="sm" variant="default" onClick={() => handleUseTemplate(t)}>
                <Send className="h-4 w-4 mr-1" /> Use
              </Button>
            </div>
          </Card>
        ))}
        {templates.length === 0 && !loading && (
          <div className="col-span-full text-center py-16 text-muted-foreground">No templates yet. Create your first template to get started.</div>
        )}
      </div>

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>{editId ? "Edit Template" : "Create Template"}</DialogTitle>
            <DialogDescription>Fill in the template details below.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Template Name</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
              <div className="space-y-2"><Label>Subject Line</Label><Input value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} /></div>
            </div>
            <div className="space-y-2"><Label>Description</Label><Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} /></div>
            <div className="space-y-2"><Label>Body (HTML)</Label><Textarea className="min-h-[200px] font-mono text-sm" value={form.body_html} onChange={(e) => setForm({ ...form, body_html: e.target.value })} /></div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>Cancel</Button>
            <Button onClick={handleSave}>Save Template</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Compose / Notify Owners dialog with pre-filled template */}
      <NotifyOwnersDialog 
        open={showCompose} 
        onOpenChange={setShowCompose} 
        initialTemplate={composeTemplate}
      />
    </div>
  );
}

export default function EmailTemplatesPage() {
  return (
    <NotifyOwnersProvider>
      <EmailTemplatesPageContent />
    </NotifyOwnersProvider>
  );
}
