'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { toast } from 'react-toastify';

interface Tpl {
  id: number; name: string; channel: 'EMAIL' | 'WHATSAPP' | 'SMS'; channel_label: string;
  purpose: 'GENERAL' | 'OTP';
  subject: string; body: string; provider_template_name: string; is_active: boolean;
}

const CHANNELS = [
  { v: 'EMAIL', label: 'Email', icon: 'fa-solid fa-envelope', color: 'text-indigo-600' },
  { v: 'WHATSAPP', label: 'WhatsApp', icon: 'fa-brands fa-whatsapp', color: 'text-emerald-600' },
  { v: 'SMS', label: 'SMS', icon: 'fa-solid fa-comment-sms', color: 'text-amber-600' },
] as const;

const PLACEHOLDERS = ['{{first_name}}', '{{name}}', '{{job_title}}', '{{company}}', '{{location}}'];

const PURPOSES = [
  { v: 'GENERAL', label: 'General / Job notification' },
  { v: 'OTP', label: 'OTP (verification code)' },
] as const;

const EMPTY = { name: '', channel: 'EMAIL' as Tpl['channel'], purpose: 'GENERAL' as Tpl['purpose'], subject: '', body: '', provider_template_name: '', is_active: true };

export default function NotificationTemplatesPage() {
  const { user } = useAuth();
  const [rows, setRows] = useState<Tpl[]>([]);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState({ ...EMPTY });
  const [saving, setSaving] = useState(false);

  const unwrap = (r: any) => { const d = r?.data ?? r; return Array.isArray(d) ? d : (d?.results ?? []); };

  const load = async () => {
    setLoading(true);
    try {
      setRows(unwrap(await api.get('/notifications/templates/')) as Tpl[]);
    } catch (err) { console.error('Failed to load templates:', err); }
    finally { setLoading(false); }
  };
  useEffect(() => { if (!user) return; load(); /* eslint-disable-next-line */ }, [user]);

  const openCreate = () => { setEditId(null); setForm({ ...EMPTY }); setModal(true); };
  const openEdit = (t: Tpl) => { setEditId(t.id); setForm({ name: t.name, channel: t.channel, purpose: t.purpose || 'GENERAL', subject: t.subject, body: t.body, provider_template_name: t.provider_template_name, is_active: t.is_active }); setModal(true); };

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim() || !form.body.trim()) { toast.error('Name and body are required.'); return; }
    setSaving(true);
    try {
      if (editId) await api.patch(`/notifications/templates/${editId}/`, form);
      else await api.post('/notifications/templates/', form);
      toast.success(`Template ${editId ? 'updated' : 'created'}.`);
      setModal(false); await load();
    } catch (err: any) { toast.error(err?.data?.message || 'Could not save template.'); }
    finally { setSaving(false); }
  };

  // Templates are never deleted — only activated / deactivated. Inactive
  // templates are hidden from the send-mail dropdowns but kept on record.
  const toggleActive = async (t: Tpl) => {
    try {
      await api.patch(`/notifications/templates/${t.id}/`, { is_active: !t.is_active });
      toast.success(t.is_active ? `"${t.name}" deactivated.` : `"${t.name}" activated.`);
      await load();
    } catch { toast.error('Could not update status.'); }
  };

  const insertPlaceholder = (ph: string) => setForm((f) => ({ ...f, body: `${f.body}${ph}` }));

  const chMeta = (v: string) => CHANNELS.find((c) => c.v === v);

  if (!user) return null;

  return (
    <>
      <main className="flex-1 p-8 overflow-y-auto w-full max-w-5xl mx-auto space-y-5">
          <div className="flex items-center justify-between gap-3 flex-wrap">
            <div>
              <h2 className="text-lg font-black text-slate-800 dark:text-white">Notification Templates</h2>
              <p className="text-sm text-slate-500 dark:text-slate-400">Configure Email / WhatsApp / SMS messages for notifying candidates about jobs. Use placeholders like <code>{'{{job_title}}'}</code>.</p>
            </div>
            <button onClick={openCreate} className="px-4 py-2 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition">
              <i className="fa-solid fa-plus mr-2" />Add Template
            </button>
          </div>

          {loading ? (
            <p className="text-slate-400 text-sm">Loading…</p>
          ) : (
            <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-100 dark:border-slate-800 text-left">
                    {['Name', 'Channel', 'Subject / Body', 'Status', ''].map((h) => (
                      <th key={h} className="py-3 px-4 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50 dark:divide-slate-800">
                  {rows.length === 0 && <tr><td colSpan={5} className="py-8 text-center text-slate-400">No templates yet.</td></tr>}
                  {rows.map((t) => (
                    <tr key={t.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40">
                      <td className="py-3 px-4 font-bold text-slate-800 dark:text-white">
                        {t.name}
                        {t.purpose === 'OTP' && <span className="ml-2 text-[9px] font-extrabold px-1.5 py-0.5 bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300 align-middle">OTP</span>}
                      </td>
                      <td className="py-3 px-4">
                        <span className={`inline-flex items-center gap-1.5 text-xs font-bold ${chMeta(t.channel)?.color}`}>
                          <i className={chMeta(t.channel)?.icon} />{t.channel_label}
                        </span>
                      </td>
                      <td className="py-3 px-4 max-w-[360px]">
                        {t.subject && <p className="text-xs font-semibold text-slate-700 dark:text-slate-300 truncate">{t.subject}</p>}
                        <p className="text-xs text-slate-400 truncate">{t.body}</p>
                      </td>
                      <td className="py-3 px-4">
                        <button
                          onClick={() => toggleActive(t)}
                          title={t.is_active ? 'Click to deactivate' : 'Click to activate'}
                          className={`text-[10px] font-bold px-2 py-0.5 border cursor-pointer transition ${t.is_active ? 'bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100 dark:bg-emerald-950/40 dark:text-emerald-300' : 'bg-slate-100 text-slate-500 border-slate-200 hover:bg-slate-200 dark:bg-slate-800'}`}
                        >
                          {t.is_active ? 'Active' : 'Inactive'}
                        </button>
                      </td>
                      <td className="py-3 px-4 text-right whitespace-nowrap">
                        <button onClick={() => openEdit(t)} title="Edit" className="w-8 h-8 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 mr-2"><i className="fa-solid fa-pen text-xs" /></button>
                        <button
                          onClick={() => toggleActive(t)}
                          title={t.is_active ? 'Deactivate' : 'Activate'}
                          className={`w-8 h-8 border transition ${t.is_active
                            ? 'border-amber-200 text-amber-600 hover:bg-amber-500 hover:text-white dark:border-amber-900/50 dark:text-amber-400'
                            : 'border-emerald-200 text-emerald-600 hover:bg-emerald-600 hover:text-white dark:border-emerald-900/50 dark:text-emerald-400'}`}
                        >
                          <i className={`fa-solid ${t.is_active ? 'fa-toggle-off' : 'fa-toggle-on'} text-xs`} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
      </main>

      {modal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto">
          <form onSubmit={save} className="w-full max-w-lg my-6 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-xl">
            <div className="flex items-center justify-between border-b border-slate-100 dark:border-slate-800 p-5">
              <h3 className="text-base font-black text-slate-800 dark:text-white">{editId ? 'Edit' : 'Add'} Template</h3>
              <button type="button" onClick={() => setModal(false)} className="text-slate-400 hover:text-slate-600">✕</button>
            </div>
            <div className="p-5 space-y-4">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Name</label>
                  <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} autoFocus
                    className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
                </div>
                <div>
                  <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Channel</label>
                  <select value={form.channel} onChange={(e) => setForm({ ...form, channel: e.target.value as Tpl['channel'] })}
                    className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]">
                    {CHANNELS.map((c) => <option key={c.v} value={c.v}>{c.label}</option>)}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Purpose</label>
                <select value={form.purpose} onChange={(e) => setForm({ ...form, purpose: e.target.value as Tpl['purpose'] })}
                  className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]">
                  {PURPOSES.map((p) => <option key={p.v} value={p.v}>{p.label}</option>)}
                </select>
                {form.purpose === 'OTP' && (
                  <p className="text-[10px] text-amber-600 dark:text-amber-400 mt-1">The active OTP template for this channel is used when sending verification codes. Use <code>{'{{otp}}'}</code> in the body.</p>
                )}
              </div>

              {form.channel === 'EMAIL' && (
                <div>
                  <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Subject</label>
                  <input value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })}
                    className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
                </div>
              )}

              {form.channel === 'WHATSAPP' && (
                <div>
                  <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Approved WhatsApp template name</label>
                  <input value={form.provider_template_name} onChange={(e) => setForm({ ...form, provider_template_name: e.target.value })}
                    placeholder="e.g. job_alert / otp_1"
                    className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
                  <p className="text-[10px] text-slate-400 mt-1">The template name approved on the WhatsApp gateway (send2.digital).</p>
                </div>
              )}
              {form.channel === 'SMS' && (
                <div>
                  <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">DLT content-id (approved SMS template)</label>
                  <input value={form.provider_template_name} onChange={(e) => setForm({ ...form, provider_template_name: e.target.value })}
                    placeholder="e.g. 1207167109514548068"
                    className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
                  <p className="text-[10px] text-slate-400 mt-1">The DLT content-id registered for this exact message text. Required for delivery.</p>
                </div>
              )}

              <div>
                <label className="block text-[11px] font-bold uppercase text-slate-500 mb-1">Message body</label>
                <textarea rows={5} value={form.body} onChange={(e) => setForm({ ...form, body: e.target.value })}
                  className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
                <div className="flex flex-wrap gap-1.5 mt-2">
                  {(form.purpose === 'OTP' ? ['{{otp}}', ...PLACEHOLDERS] : PLACEHOLDERS).map((ph) => (
                    <button key={ph} type="button" onClick={() => insertPlaceholder(ph)}
                      className="text-[10px] font-mono px-2 py-1 bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-[#405189] hover:text-white transition">{ph}</button>
                  ))}
                </div>
              </div>

              <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 cursor-pointer">
                <input type="checkbox" checked={form.is_active} onChange={(e) => setForm({ ...form, is_active: e.target.checked })} className="w-4 h-4 accent-[#405189]" />
                Active
              </label>
            </div>
            <div className="flex justify-end gap-2 border-t border-slate-100 dark:border-slate-800 p-5">
              <button type="button" onClick={() => setModal(false)} className="px-4 py-2 border border-slate-200 dark:border-slate-700 text-sm font-semibold">Cancel</button>
              <button type="submit" disabled={saving} className="px-6 py-2 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">{saving ? 'Saving…' : 'Save'}</button>
            </div>
          </form>
        </div>
      )}
    </>
  );
}
