'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { fillTemplate } from '@/lib/template-placeholders';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type Template = { id: number; name: string; category: string; subject: string; body: string; isBuiltIn: boolean };
type ClientLookup = { id: number; name: string; company: string | null; phone: string; email: string | null };

export default function EmailCampaignsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [templates, setTemplates] = useState<Template[]>([]);
  const [clients, setClients] = useState<ClientLookup[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [preview, setPreview] = useState<Template | null>(null);
  const [sendClientId, setSendClientId] = useState('');
  const [sending, setSending] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [t, c] = await Promise.all([
        adminApiFetch('/admin/email/templates', accessToken, appSecretProof),
        adminApiFetch('/admin/billing/clients-lookup', accessToken, appSecretProof),
      ]);
      setTemplates(t.templates || []);
      setClients(c.clients || []);
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  const previewValues = { clientName: '[Client Name]', quoteTotal: '4,130,000', crbNo: 'SPM2/308/07/2022', poBox: '35980' };

  async function sendCampaign() {
    if (!accessToken || !appSecretProof || !preview || !sendClientId) return;
    const client = clients.find((c) => c.id === Number(sendClientId));
    if (!client?.email) { show('error', 'This client has no email on file.'); return; }
    setSending(true);
    try {
      const values = { clientName: client.name, quoteTotal: previewValues.quoteTotal, crbNo: previewValues.crbNo, poBox: previewValues.poBox };
      await adminApiFetch('/admin/email/send', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          toEmail: client.email, clientId: client.id,
          subject: fillTemplate(preview.subject, values),
          body: fillTemplate(preview.body, values),
        }),
      });
      show('success', `"${preview.name}" sent to ${client.name}.`);
      setPreview(null);
      setSendClientId('');
    } catch { show('error', 'Could not send that campaign.'); }
    finally { setSending(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Email Campaigns</h1>
      <p className="text-xs text-gray-500 -mt-3">Reusable templates for the sales lifecycle — preview, then send to a specific client with their details filled in.</p>

      {loading ? <TableSkeleton rows={4} cols={3} /> : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {templates.map((t) => (
            <div key={t.id} className="bg-white border border-brand-border rounded-xl p-4 transition-all hover:shadow-md hover:-translate-y-0.5">
              <p className="font-bold text-sm">{t.name}</p>
              <p className="text-[10px] text-gray-400 mt-1">Variables: {'{{clientName}}'} {'{{quoteTotal}}'} {'{{crbNo}}'} {'{{poBox}}'}</p>
              <div className="bg-brand-bg rounded-lg p-3 mt-3 h-20 overflow-hidden text-[10px] text-gray-500 relative">
                {fillTemplate(t.body, previewValues).slice(0, 140)}…
                <div className="absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-brand-bg to-transparent" />
              </div>
              <button onClick={() => setPreview(t)} className="mt-3 w-full border border-brand-border rounded-lg py-1.5 text-xs transition-colors hover:bg-brand-bg">
                Preview &amp; Send
              </button>
            </div>
          ))}
          {templates.length === 0 && <p className="text-xs text-gray-400 col-span-3">No templates yet.</p>}
        </div>
      )}

      {preview && (
        <Modal title={preview.name} onClose={() => setPreview(null)} wide>
          <div className="space-y-3">
            <div className="bg-brand-bg rounded-lg p-3 text-xs">
              <p className="font-semibold mb-1">Subject: {fillTemplate(preview.subject, previewValues)}</p>
              <p className="whitespace-pre-wrap text-gray-600">{fillTemplate(preview.body, previewValues)}</p>
            </div>
            <p className="text-[10px] text-gray-400">Logo &bull; Phones &bull; CRB {previewValues.crbNo} &bull; Preview shown with sample values — real client details substitute automatically on send.</p>

            <div className="flex gap-2">
              <select value={sendClientId} onChange={(e) => setSendClientId(e.target.value)}
                className="flex-1 border border-brand-border rounded-lg px-2 py-1.5 text-sm">
                <option value="">Send to client…</option>
                {clients.map((c) => <option key={c.id} value={c.id}>{c.name} {c.email ? '' : '(no email)'}</option>)}
              </select>
              <button onClick={sendCampaign} disabled={sending || !sendClientId} className="bg-brand-red text-white text-sm font-semibold px-4 rounded-lg disabled:opacity-60">
                {sending ? 'Sending…' : 'Send'}
              </button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}
