'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { EMAIL_CATEGORIES, type EmailPreferences } from '@/lib/domain/email-policy'

/**
 * Preference center form (2026-09-22, §9) — used on Settings (signed in) and
 * on the public /email/preferences/<token> page. Required categories are
 * shown locked; "Unsubscribe from all updates" turns every updates category
 * off and leaves account, trip and permit mail alone.
 */
async function call(body: Record<string, unknown>) {
  const r = await fetch('/api/email/preferences', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
  const json = await r.json().catch(() => ({}))
  if (!r.ok) throw new Error(json.error ?? 'Something went wrong.')
  return json
}

export function EmailPreferencesForm({ initial, token, hasAccount, available }: { initial: EmailPreferences; token?: string; hasAccount: boolean; available: boolean }) {
  const [prefs, setPrefs] = useState(initial)
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState<string | null>(null)
  async function run(fn: () => Promise<string>) {
    setBusy(true)
    try { setDone(await fn()) } catch (e) { toast.error(e instanceof Error ? e.message : 'Something went wrong.') } finally { setBusy(false) }
  }
  const updates = EMAIL_CATEGORIES.filter((c) => c.stream === 'updates')
  const operational = EMAIL_CATEGORIES.filter((c) => c.stream === 'transactional')
  const Row = ({ c }: { c: (typeof EMAIL_CATEGORIES)[number] }) => (
    <label className={`flex items-start gap-3 rounded-lg border p-3 ${c.required ? 'bg-neutral-50' : 'bg-white'}`}>
      <input type="checkbox" className="mt-0.5 h-4 w-4" disabled={c.required || !hasAccount || !available} checked={c.required ? true : !!prefs[c.preferenceField!]} onChange={(e) => c.preferenceField && setPrefs((p) => ({ ...p, [c.preferenceField!]: e.target.checked }))} />
      <span className="min-w-0">
        <span className="block text-sm font-semibold">{c.label}{c.required && <span className="ml-2 rounded bg-neutral-200 px-1.5 py-0.5 text-[10px] font-bold uppercase text-neutral-700">Required</span>}</span>
        <span className="block text-xs text-neutral-500">{c.description}</span>
      </span>
    </label>
  )
  return (
    <div className="space-y-4">
      {!available && <p className="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">Email preferences need database migration 0028. Unsubscribing from updates still works.</p>}
      {done && <p className="rounded-lg bg-green-50 p-3 text-sm text-green-800">{done}</p>}
      <div>
        <p className="text-[11px] font-bold uppercase tracking-wide text-neutral-500">Account &amp; operations — from info@heavyhaulagent.com</p>
        <div className="mt-2 grid gap-2">{operational.map((c) => <Row key={c.key} c={c} />)}</div>
        {!hasAccount && <p className="mt-1 text-[11px] text-neutral-500">Operational categories apply to HeavyHaul Agent accounts.</p>}
      </div>
      <div>
        <p className="text-[11px] font-bold uppercase tracking-wide text-neutral-500">Updates &amp; campaigns — from updates@heavyhaulagent.com</p>
        <div className="mt-2 grid gap-2">{updates.map((c) => <Row key={c.key} c={c} />)}</div>
      </div>
      <div className="flex flex-wrap gap-2">
        {hasAccount && available && <button disabled={busy} onClick={() => run(async () => { await call({ op: 'save', token, prefs }); return 'Preferences saved.' })} className="rounded-lg bg-[#0f1b2d] px-4 py-2 text-sm font-bold text-white disabled:opacity-50">Save preferences</button>}
        <button disabled={busy} onClick={() => run(async () => { await call({ op: 'unsubscribe_updates', token }); setPrefs((p) => ({ ...p, product_updates: false, newsletter: false, marketing_campaigns: false, pilot_opportunities: false, broker_opportunities: false, carrier_opportunities: false })); return 'You are unsubscribed from all HeavyHaul Agent updates. Account, trip and permit emails are not affected.' })} className="rounded-lg border px-4 py-2 text-sm font-bold text-neutral-800 disabled:opacity-50">Unsubscribe from all updates</button>
      </div>
    </div>
  )
}
