"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { emailTemplatesApi, EmailTemplate } from "@/lib/api";

export default function EmailTemplatesPage() {
    const router = useRouter();
    const [templates, setTemplates] = useState<EmailTemplate[]>([]);
    const [loading, setLoading] = useState(true);
    const [showCreate, setShowCreate] = useState(false);
    const [newTemplate, setNewTemplate] = useState({ slug: "", subject: "", body_html: "", variables: "" });

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

    const fetchTemplates = async () => {
        try {
            const data = await emailTemplatesApi.list();
            setTemplates(data || []);
        } catch (err: any) {
            toast.error(err.message || "Failed to load templates");
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = async () => {
        if (!newTemplate.slug || !newTemplate.subject) {
            toast.error("Slug and Subject are required");
            return;
        }
        try {
            const vars = newTemplate.variables.split(",").map(v => v.trim()).filter(Boolean);
            await emailTemplatesApi.create({
                slug: newTemplate.slug,
                subject: newTemplate.subject,
                body_html: newTemplate.body_html,
                variables: vars,
            });
            toast.success("Template created");
            setShowCreate(false);
            setNewTemplate({ slug: "", subject: "", body_html: "", variables: "" });
            fetchTemplates();
        } catch (err: any) {
            toast.error(err.message || "Failed to create template");
        }
    };

    const handleDelete = async (slug: string) => {
        if (!confirm("Delete this template?")) return;
        try {
            await emailTemplatesApi.delete(slug);
            toast.success("Template deleted");
            fetchTemplates();
        } catch (err: any) {
            toast.error(err.message || "Failed to delete template");
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        );
    }

    return (
        <div className="max-w-5xl mx-auto p-6">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold">Email Templates</h1>
                <button
                    onClick={() => setShowCreate(!showCreate)}
                    className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition"
                >
                    {showCreate ? "Cancel" : "+ New Template"}
                </button>
            </div>

            {showCreate && (
                <div className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-md mb-6">
                    <h2 className="text-lg font-semibold mb-4">Create Template</h2>
                    <div className="space-y-4">
                        <div>
                            <label className="block text-sm font-medium mb-1">Slug</label>
                            <input
                                type="text"
                                value={newTemplate.slug}
                                onChange={(e) => setNewTemplate({ ...newTemplate, slug: e.target.value })}
                                placeholder="welcome-user"
                                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium mb-1">Subject</label>
                            <input
                                type="text"
                                value={newTemplate.subject}
                                onChange={(e) => setNewTemplate({ ...newTemplate, subject: e.target.value })}
                                placeholder="Welcome to GoHorse Jobs!"
                                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium mb-1">Body (HTML)</label>
                            <textarea
                                value={newTemplate.body_html}
                                onChange={(e) => setNewTemplate({ ...newTemplate, body_html: e.target.value })}
                                rows={5}
                                placeholder="<h1>Hello {{name}}</h1>"
                                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary font-mono text-sm"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium mb-1">Variables (comma-separated)</label>
                            <input
                                type="text"
                                value={newTemplate.variables}
                                onChange={(e) => setNewTemplate({ ...newTemplate, variables: e.target.value })}
                                placeholder="name, link"
                                className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary"
                            />
                        </div>
                        <button
                            onClick={handleCreate}
                            className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
                        >
                            Create
                        </button>
                    </div>
                </div>
            )}

            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
                <table className="w-full">
                    <thead className="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th className="px-4 py-3 text-left text-sm font-semibold">Slug</th>
                            <th className="px-4 py-3 text-left text-sm font-semibold">Subject</th>
                            <th className="px-4 py-3 text-left text-sm font-semibold">Variables</th>
                            <th className="px-4 py-3 text-right text-sm font-semibold">Actions</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-600">
                        {templates.map((tmpl) => (
                            <tr key={tmpl.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                                <td className="px-4 py-3 font-mono text-sm">{tmpl.slug}</td>
                                <td className="px-4 py-3">{tmpl.subject}</td>
                                <td className="px-4 py-3 text-sm text-gray-500">
                                    {(tmpl.variables || []).join(", ")}
                                </td>
                                <td className="px-4 py-3 text-right space-x-2">
                                    <button
                                        onClick={() => router.push(`/dashboard/admin/email-templates/${tmpl.slug}`)}
                                        className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
                                    >
                                        Edit
                                    </button>
                                    <button
                                        onClick={() => handleDelete(tmpl.slug)}
                                        className="px-3 py-1 text-sm bg-red-500 text-white rounded hover:bg-red-600"
                                    >
                                        Delete
                                    </button>
                                </td>
                            </tr>
                        ))}
                        {templates.length === 0 && (
                            <tr>
                                <td colSpan={4} className="px-4 py-8 text-center text-gray-500">
                                    No email templates found. Create one to get started.
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
}
