'use client';

import { useEffect, useRef, useState } from 'react';
import { Loader2, FileText, Save, RotateCcw } from 'lucide-react';
import { toast } from 'sonner';

interface TemplateListRow {
  key: string;
  audience: 'customer' | 'restaurant' | 'platform';
  subject: string;
  html: string;
  defaultSubject: string;
  defaultHtml: string;
  overridden: boolean;
  updatedAt: string | null;
}

interface TemplateDetail extends TemplateListRow {
  sampleVars: Record<string, unknown>;
  preview: { subject: string; html: string };
}

function humanizeKey(key: string) {
  return key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

export default function AdminEmailTemplatesPage() {
  const [list, setList] = useState<TemplateListRow[]>([]);
  const [active, setActive] = useState<TemplateDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const previewTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const previewSeq = useRef(0);

  const reload = async () => {
    setLoading(true);
    const r = await fetch('/api/admin/email/templates', { credentials: 'include' });
    const d = await r.json();
    setList(d.templates || []);
    setLoading(false);
  };
  useEffect(() => { reload(); }, []);

  useEffect(() => {
    if (!active) return;
    if (previewTimer.current) clearTimeout(previewTimer.current);
    const key = active.key;
    const subject = active.subject;
    const html = active.html;
    previewTimer.current = setTimeout(async () => {
      const seq = ++previewSeq.current;
      try {
        const r = await fetch(`/api/admin/email/templates/${key}/preview`, {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ subject, html }),
        });
        if (!r.ok) return;
        const d = await r.json();
        if (seq !== previewSeq.current) return;
        setActive((prev) => (prev && prev.key === key ? { ...prev, preview: { subject: d.subject, html: d.html } } : prev));
      } catch { /* ignore preview errors */ }
    }, 400);
    return () => { if (previewTimer.current) clearTimeout(previewTimer.current); };
  }, [active?.key, active?.subject, active?.html]);

  const open = async (key: string) => {
    const r = await fetch(`/api/admin/email/templates/${key}`, { credentials: 'include' });
    const d = await r.json();
    if (d?.key) setActive(d as TemplateDetail);
  };

  const save = async () => {
    if (!active) return;
    setSaving(true);
    try {
      const r = await fetch(`/api/admin/email/templates/${active.key}`, {
        method: 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ subject: active.subject, html: active.html }),
      });
      if (!r.ok) throw new Error((await r.json()).error || 'Save failed');
      toast.success('Template saved');
      await reload();
      await open(active.key);
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Save failed'); }
    finally { setSaving(false); }
  };

  const reset = async () => {
    if (!active) return;
    if (!confirm(`Reset "${humanizeKey(active.key)}" to default?`)) return;
    const r = await fetch(`/api/admin/email/templates/${active.key}`, { method: 'DELETE', credentials: 'include' });
    if (r.ok) { toast.success('Reverted to default'); await reload(); await open(active.key); }
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex items-center gap-3 mb-6">
        <FileText className="text-orange-500" />
        <h1 className="text-2xl font-semibold">Email Templates</h1>
      </div>

      {loading ? (
        <div className="flex justify-center p-8"><Loader2 className="animate-spin" /></div>
      ) : (
        <div className="grid grid-cols-12 gap-6">
          <div className="col-span-4 bg-white rounded-lg border divide-y max-h-[70vh] overflow-y-auto">
            {list.map((t) => (
              <button key={t.key} onClick={() => open(t.key)}
                      className={`w-full text-left px-4 py-3 hover:bg-orange-50 ${active?.key === t.key ? 'bg-orange-50' : ''}`}>
                <div className="font-medium text-sm">{humanizeKey(t.key)}</div>
                <div className="text-xs text-gray-500 flex items-center gap-2">
                  <span className="uppercase">{t.audience}</span>
                  {t.overridden && <span className="text-orange-600">• customized</span>}
                </div>
              </button>
            ))}
          </div>

          <div className="col-span-8">
            {!active ? (
              <div className="bg-white border rounded-lg p-8 text-center text-gray-500">Select a template to edit</div>
            ) : (
              <div className="bg-white border rounded-lg p-6 space-y-4">
                <div className="flex justify-between items-start">
                  <div>
                    <h2 className="text-lg font-semibold">{humanizeKey(active.key)}</h2>
                    <div className="text-xs text-gray-500">key: <code>{active.key}</code> · audience: {active.audience}</div>
                  </div>
                  {active.overridden && (
                    <button onClick={reset} className="text-sm text-gray-600 hover:text-red-600 inline-flex items-center gap-1">
                      <RotateCcw size={14} /> Reset to default
                    </button>
                  )}
                </div>

                <label className="block">
                  <span className="block text-xs font-medium text-gray-600 mb-1">Subject</span>
                  <input className="w-full border rounded-md px-3 py-2" value={active.subject}
                         onChange={(e) => setActive({ ...active, subject: e.target.value })} />
                </label>

                <label className="block">
                  <span className="block text-xs font-medium text-gray-600 mb-1">HTML body (use <code>{'{{varName}}'}</code> placeholders)</span>
                  <textarea className="w-full border rounded-md px-3 py-2 font-mono text-xs" rows={14}
                            value={active.html}
                            onChange={(e) => setActive({ ...active, html: e.target.value })} />
                </label>

                {Object.keys(active.sampleVars || {}).length > 0 && (
                  <div className="text-xs text-gray-600">
                    <div className="font-medium mb-1">Available variables:</div>
                    <code className="text-xs">{Object.keys(active.sampleVars).join(', ')}</code>
                  </div>
                )}

                <div>
                  <div className="text-xs font-medium text-gray-600 mb-1">Live preview (using sample data)</div>
                  <div className="border rounded-md p-3 bg-gray-50">
                    <div className="text-xs text-gray-500 mb-2"><strong>Subject:</strong> {active.preview?.subject}</div>
                    <iframe title="preview" className="w-full h-[420px] bg-white border rounded" srcDoc={active.preview?.html || ''} />
                  </div>
                </div>

                <div className="flex justify-end">
                  <button disabled={saving} onClick={save}
                          className="inline-flex items-center gap-2 bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-md disabled:opacity-50">
                    {saving ? <Loader2 className="animate-spin" size={16} /> : <Save size={16} />} Save
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
