'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { leadTemplateVariables } from '@/lib/domain/broker-leads'
import type { LeadRow } from '@/lib/data/broker-leads'
import { BTN, BTN_SOFT, CARD, INPUT, Pill, call, fmtDateTime } from './shared'
import { useLeadKind } from './kind-context'

/**
 * Freight Broker Leads · Templates (Nash, 2026-09-23): "the person managing
 * freight broker leads has the full power to create the templates, change
 * them, adjust them… it should all be in here." Create, edit, activate,
 * duplicate, preview against a real lead and send a test — without the global
 * Email Templates page. Every template here is an updates-stream email in the
 * "Freight broker invitations" category, so unsubscribe always applies.
 */
interface FullTemplate {
  key: string; name: string; subject: string; body: string; footer: string; support_contact: string
  active: boolean; version: number; shipped: boolean; is_custom: boolean; updated_by: string | null; updated_at: string | null
}
interface VersionRow { id: string; template_key?: string | null; version?: number | null; subject: string; edited_by: string | null; reason: string | null; created_at: string }

const BLANK: FullTemplate = { key: '', name: '', subject: '', body: '', footer: '', support_contact: '', active: false, version: 0, shipped: false, is_custom: true, updated_by: null, updated_at: null }

export function TemplatesTab({ leads }: { leads: LeadRow[] }) {
  const cfg = useLeadKind()
  const carrier = cfg.kind === 'carrier'
  const variables = leadTemplateVariables(cfg.kind)
  const router = useRouter()
  const [templates, setTemplates] = useState<FullTemplate[] | null>(null)
  const [versions, setVersions] = useState<VersionRow[]>([])
  const [selected, setSelected] = useState<string>('')
  const [form, setForm] = useState<FullTemplate>(BLANK)
  const [isNew, setIsNew] = useState(false)
  const [reason, setReason] = useState('')
  const [busy, setBusy] = useState(false)
  const [preview, setPreview] = useState<{ subject: string; body: string } | null>(null)
  const [previewLead, setPreviewLead] = useState('')
  const [testTo, setTestTo] = useState('')
  const [error, setError] = useState<string | null>(null)

  async function load(selectKey?: string) {
    const r = await fetch(`${cfg.apiBase}/templates`)
    const json = await r.json().catch(() => ({}))
    if (!r.ok) { setError(json.error ?? 'Could not load the templates.'); setTemplates([]); return }
    setError(null)
    const list = (json.templates ?? []) as FullTemplate[]
    setTemplates(list)
    setVersions(json.versions ?? [])
    const pick = selectKey ?? selected ?? list[0]?.key
    const found = list.find((t) => t.key === pick) ?? list[0]
    if (found && !isNew) { setSelected(found.key); setForm(found) }
  }
  useEffect(() => {
    let on = true
    fetch(`${cfg.apiBase}/templates`)
      .then(async (r) => ({ ok: r.ok, json: await r.json().catch(() => ({})) }))
      .then(({ ok, json }) => {
        if (!on) return
        if (!ok) { setError(json.error ?? 'Could not load the templates.'); setTemplates([]); return }
        const list = (json.templates ?? []) as FullTemplate[]
        setTemplates(list); setVersions(json.versions ?? [])
        if (list[0]) { setSelected(list[0].key); setForm(list[0]) }
      })
    return () => { on = false }
  }, [cfg.apiBase])

  const set = <K extends keyof FullTemplate>(k: K, v: FullTemplate[K]) => setForm((f) => ({ ...f, [k]: v }))
  function select(t: FullTemplate) { setIsNew(false); setSelected(t.key); setForm(t); setPreview(null); setReason('') }
  function startNew() { setIsNew(true); setSelected(''); setForm({ ...BLANK, body: 'Hello {{first_name}},\n\n…\n\nGet started: {{join_link}}\n\nQuestions? {{support_email}}' }); setPreview(null) }

  async function save(activeOverride?: boolean) {
    setBusy(true)
    try {
      await call(`${cfg.apiBase}/templates`, { op: 'save', key: form.key, name: form.name, subject: form.subject, body: form.body, footer: form.footer, support_contact: form.support_contact, active: activeOverride ?? form.active, reason: reason || undefined })
      toast.success(isNew ? 'Template created — activate it to use it in a campaign.' : 'Template saved. A version was recorded.')
      setReason(''); setIsNew(false)
      await load(form.key)
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not save.') } finally { setBusy(false) }
  }
  async function duplicate() {
    const newKey = prompt('Key for the copy (lowercase letters, digits, underscores):', `${form.key}_v2`)
    if (!newKey) return
    setBusy(true)
    try {
      await call(`${cfg.apiBase}/templates`, { op: 'duplicate', key: form.key, new_key: newKey.trim(), name: `${form.name} (copy)` })
      toast.success('Copied. The copy starts inactive so you can edit it safely.')
      await load(newKey.trim())
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not duplicate.') } finally { setBusy(false) }
  }
  async function doPreview() {
    setBusy(true)
    try { setPreview(await call(`${cfg.apiBase}/templates`, { op: 'preview', key: form.key, subject: form.subject, body: form.body, lead_id: previewLead || undefined })) }
    catch (e) { toast.error(e instanceof Error ? e.message : 'Could not render the preview.') } finally { setBusy(false) }
  }
  async function sendTest() {
    setBusy(true)
    try { const r = await call<{ status: string }>(`${cfg.apiBase}/templates`, { op: 'test', key: form.key, to: testTo }); toast.success(r.status === 'sent' ? `Test sent to ${testTo}.` : `Recorded for ${testTo} — ${r.status.replace(/_/g, ' ')}.`) }
    catch (e) { toast.error(e instanceof Error ? e.message : 'Could not send the test.') } finally { setBusy(false) }
  }

  const mine = versions.filter((v) => v.template_key === form.key).slice(0, 8)
  const previewLeads = (carrier ? leads : leads.filter((l) => l.brokerage_name)).slice(0, 25)

  return (
    <div className="space-y-4">
      <p className="text-xs text-neutral-500">These are the emails your campaigns send. Every one goes out on the updates stream with an unsubscribe link, and each save keeps a version you can look back at. Activate a template before a campaign can use it.</p>
      {error && <p className="rounded-lg bg-amber-50 p-3 text-xs text-amber-900">{error}</p>}
      <div className="grid gap-4 lg:grid-cols-[260px_1fr]">
        <div className="space-y-2">
          {templates === null ? <p className="text-xs text-neutral-500">Loading…</p> : templates.map((t) => (
            <button key={t.key} onClick={() => select(t)} className={`w-full rounded-xl border p-2.5 text-left ${t.key === selected && !isNew ? 'border-[#0f1b2d] bg-[#0f1b2d] text-white' : 'bg-white hover:bg-neutral-50'}`}>
              <p className="text-sm font-semibold">{t.name}</p>
              <p className={`text-[11px] ${t.key === selected && !isNew ? 'text-neutral-300' : 'text-neutral-500'}`}>{t.key} · v{t.version}{t.active ? '' : ' · INACTIVE'}{t.shipped ? '' : ' · custom'}</p>
            </button>
          ))}
          <button onClick={startNew} className={`${BTN_SOFT} w-full`}>+ Create template</button>
        </div>

        <div className={CARD}>
          <div className="flex flex-wrap items-center justify-between gap-2">
            <h3 className="text-sm font-bold">{isNew ? 'New template' : form.name || 'Template'}</h3>
            <div className="flex items-center gap-3 text-xs">
              {!isNew && <Pill tone={form.active ? 'success' : 'danger'}>{form.active ? 'active' : 'inactive'}</Pill>}
              <label className="flex cursor-pointer items-center gap-1.5 font-semibold"><input type="checkbox" checked={form.active} onChange={(e) => set('active', e.target.checked)} /> Active</label>
            </div>
          </div>
          {!isNew && form.updated_at && <p className="mt-0.5 text-[11px] text-neutral-400">v{form.version} · last changed {fmtDateTime(form.updated_at)}{form.updated_by ? ` by ${form.updated_by}` : ''}</p>}

          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <label className="text-xs font-semibold text-neutral-600">Key{isNew ? '' : ' (fixed)'}<input className={`${INPUT} mt-1 block w-full`} value={form.key} disabled={!isNew} onChange={(e) => set('key', e.target.value)} placeholder={carrier ? 'carrier_lead_second_touch' : 'broker_lead_second_touch'} /></label>
            <label className="text-xs font-semibold text-neutral-600">Name<input className={`${INPUT} mt-1 block w-full`} value={form.name} onChange={(e) => set('name', e.target.value)} placeholder={carrier ? 'Carrier Lead — Second touch' : 'Freight Broker Lead — Second touch'} /></label>
          </div>
          <label className="mt-2 block text-xs font-semibold text-neutral-600">Subject<input className={`${INPUT} mt-1 block w-full`} value={form.subject} onChange={(e) => set('subject', e.target.value)} /></label>
          <label className="mt-2 block text-xs font-semibold text-neutral-600">Body<textarea rows={14} className={`${INPUT} mt-1 block w-full font-mono text-xs`} value={form.body} onChange={(e) => set('body', e.target.value)} /></label>
          <div className="mt-2 grid gap-2 sm:grid-cols-2">
            <label className="text-xs font-semibold text-neutral-600">Footer (optional)<input className={`${INPUT} mt-1 block w-full`} value={form.footer} onChange={(e) => set('footer', e.target.value)} /></label>
            <label className="text-xs font-semibold text-neutral-600">Support contact (optional)<input className={`${INPUT} mt-1 block w-full`} value={form.support_contact} onChange={(e) => set('support_contact', e.target.value)} /></label>
          </div>

          <div className="mt-2 flex flex-wrap gap-1.5">
            {variables.map((v) => (
              <button key={v} type="button" onClick={() => { void navigator.clipboard?.writeText(`{{${v}}}`); toast.success(`{{${v}}} copied`) }} className="rounded border bg-neutral-50 px-1.5 py-0.5 font-mono text-[10px] text-neutral-600 hover:bg-neutral-100">{`{{${v}}}`}</button>
            ))}
          </div>
          <p className="mt-1 text-[10px] text-neutral-400">Click a variable to copy it. A line whose variable has no value is left out of the sent email — never printed empty. The unsubscribe and preference links are added automatically.</p>

          {!isNew && <label className="mt-3 block text-xs font-semibold text-neutral-600">Why are you changing this? (kept with the version)<input className={`${INPUT} mt-1 block w-full`} value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Shorter subject for wave 2" /></label>}

          <div className="mt-3 flex flex-wrap items-center gap-2">
            <button disabled={busy || !form.key || !form.name || !form.subject || !form.body} onClick={() => save()} className={BTN}>{busy ? 'Saving…' : isNew ? 'Create template' : 'Save template'}</button>
            {!isNew && <button disabled={busy} onClick={() => save(!form.active)} className={BTN_SOFT}>{form.active ? 'Deactivate' : 'Activate'}</button>}
            {!isNew && <button disabled={busy} onClick={duplicate} className={BTN_SOFT}>Duplicate</button>}
          </div>

          <div className="mt-4 border-t pt-3">
            <div className="flex flex-wrap items-end gap-2">
              <label className="text-xs font-semibold text-neutral-600">Preview as<select className={`${INPUT} mt-1 block w-56`} value={previewLead} onChange={(e) => setPreviewLead(e.target.value)}><option value="">sample data</option>{previewLeads.map((l) => <option key={l.id} value={l.id}>{[l.first_name, l.last_name].filter(Boolean).join(' ') || l.email}{l.brokerage_name ? ` — ${l.brokerage_name}` : ''}</option>)}</select></label>
              <button disabled={busy || !form.body} onClick={doPreview} className={BTN_SOFT}>Preview</button>
              <label className="text-xs font-semibold text-neutral-600">Send a test to<input className={`${INPUT} mt-1 block w-56`} value={testTo} onChange={(e) => setTestTo(e.target.value)} placeholder="you@heavyhaulagent.com" /></label>
              <button disabled={busy || isNew || !testTo.includes('@')} onClick={sendTest} className={BTN_SOFT}>Send test</button>
            </div>
            {preview && (
              <div className="mt-3 rounded-xl border bg-neutral-50 p-3">
                <p className="text-xs font-bold">{preview.subject}</p>
                <pre className="mt-2 whitespace-pre-wrap font-sans text-xs text-neutral-700">{preview.body}</pre>
              </div>
            )}
          </div>

          {mine.length > 0 && (
            <details className="mt-3 text-xs">
              <summary className="cursor-pointer font-semibold text-neutral-600">Version history ({mine.length})</summary>
              <ul className="mt-1 space-y-0.5 text-neutral-500">
                {mine.map((v) => <li key={v.id}>v{v.version ?? '?'} · {fmtDateTime(v.created_at)} · {v.edited_by ?? 'unknown'}{v.reason ? ` — ${v.reason}` : ''}<br /><span className="text-neutral-400">{v.subject}</span></li>)}
              </ul>
            </details>
          )}
        </div>
      </div>
    </div>
  )
}
