'use client'

import { useMemo, useState } from 'react'
import { ArrowRight, CheckCircle2, Mail, RotateCcw, ShieldAlert } from 'lucide-react'
import { renderTemplateClean } from '@/lib/email-templates'
import {
  DEMO_MATCHING_PERMIT, DEMO_SMALL_PERMIT, DEMO_TRIP_DIMENSIONS, demoDimensionWarnings,
  type DemoDimensions, type DemoMeasure,
} from '@/lib/demo/dimension-alert'

type Run = { id: number; outcome: 'sent' | 'skipped' | 'clear'; details: string }

const FIELDS: Array<{ key: DemoMeasure; label: string; unit: string }> = [
  { key: 'length', label: 'Length', unit: 'in' },
  { key: 'width', label: 'Width', unit: 'in' },
  { key: 'height', label: 'Height', unit: 'in' },
  { key: 'weight', label: 'Gross weight', unit: 'lb' },
]

function format(value: number | null, unit: string) {
  if (value === null) return 'Not provided'
  if (unit === 'lb') return `${value.toLocaleString('en-US')} lb`
  return `${Math.floor(value / 12)}′ ${value % 12}″`
}

function DimCard({ title, dimensions, editable, onChange }: {
  title: string
  dimensions: DemoDimensions
  editable?: boolean
  onChange?: (key: DemoMeasure, value: number | null) => void
}) {
  return (
    <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <h2 className="text-sm font-bold uppercase tracking-widest text-slate-500">{title}</h2>
      <div className="mt-4 grid grid-cols-2 gap-3">
        {FIELDS.map(({ key, label, unit }) => (
          <label key={key} className="block">
            <span className="text-xs font-semibold text-slate-500">{label}</span>
            {editable ? (
              <div className="mt-1 flex items-center rounded-lg border border-slate-300 bg-slate-50 focus-within:ring-2 focus-within:ring-amber-400">
                <input
                  aria-label={`Permit ${label.toLowerCase()}`}
                  className="w-full min-w-0 bg-transparent px-3 py-2 text-sm font-semibold text-slate-900 outline-none"
                  type="number"
                  min="0"
                  step="1"
                  value={dimensions[key] ?? ''}
                  placeholder="—"
                  onChange={(event) => {
                    const raw = event.target.value
                    onChange?.(key, raw === '' ? null : Math.max(0, Math.round(Number(raw))))
                  }}
                />
                <span className="pr-3 text-xs text-slate-500">{unit}</span>
              </div>
            ) : (
              <div className="mt-1 rounded-lg bg-slate-100 px-3 py-2 text-sm font-semibold text-slate-900">{format(dimensions[key], unit)}</div>
            )}
          </label>
        ))}
      </div>
    </section>
  )
}

export function DimensionAlertDemo({ subjectTemplate, bodyTemplate }: { subjectTemplate: string; bodyTemplate: string }) {
  const [permitDimensions, setPermitDimensions] = useState<DemoDimensions>(DEMO_SMALL_PERMIT)
  const [sentKeys, setSentKeys] = useState<string[]>([])
  const [runs, setRuns] = useState<Run[]>([])
  const [lastCheckedDimensions, setLastCheckedDimensions] = useState('')
  const [testTo, setTestTo] = useState('')
  const [testBusy, setTestBusy] = useState(false)
  const [testResult, setTestResult] = useState('')

  const warnings = useMemo(() => demoDimensionWarnings(permitDimensions), [permitDimensions])

  // Production hashes these sorted warning messages with SHA-256. The demo
  // retains the same sorted input to illustrate which changes cause a new send.
  const alertKey = warnings.map((warning) => warning.message).sort().join('\n')
  const dimensionsKey = JSON.stringify(permitDimensions)
  const latest = runs[0]
  const dimensionsChanged = !!latest && lastCheckedDimensions !== dimensionsKey
  const previewData = {
    trip_id: 'HH-123456789', permit_number: 'GA-48392', permit_state: 'GA',
    permit_source: 'Synchron Permits',
    mismatch_rows: warnings.map((warning) => `- ${warning.message}`).join('\n'),
    workspace_link: 'https://heavyhaulagent.com/fb-trip-workspace/HH-123456789',
  }
  const subject = renderTemplateClean(subjectTemplate, previewData)
  const body = renderTemplateClean(bodyTemplate, previewData)

  function runCheck() {
    const outcome: Run['outcome'] = !warnings.length ? 'clear' : sentKeys.includes(alertKey) ? 'skipped' : 'sent'
    if (outcome === 'sent') setSentKeys((previous) => [...previous, alertKey])
    setLastCheckedDimensions(dimensionsKey)
    const details = outcome === 'sent'
      ? `${warnings.length} mismatch${warnings.length === 1 ? '' : 'es'} found. Broker and dispatcher would each receive one email.`
      : outcome === 'skipped'
        ? 'The same mismatch was already alerted. Duplicate email skipped for both contacts.'
        : 'Permit covers the overall trip dimensions. No email is sent.'
    setRuns((previous) => [{ id: Date.now(), outcome, details }, ...previous].slice(0, 5))
  }

  function changePermit(dimensions: DemoDimensions) {
    setPermitDimensions(dimensions)
    setTestResult('')
  }

  function reset() {
    changePermit(DEMO_SMALL_PERMIT)
    setSentKeys([])
    setRuns([])
    setLastCheckedDimensions('')
    setTestResult('')
  }

  async function sendTest() {
    setTestBusy(true)
    setTestResult('')
    try {
      const response = await fetch('/api/dev-preview/dimension-alert/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ to: testTo.trim(), permit: permitDimensions }),
      })
      const data = await response.json() as { status?: string; reason?: string | null; error?: string }
      if (!response.ok) throw new Error(data.error ?? data.reason ?? 'Test send failed.')
      setTestResult(data.status === 'sent'
        ? `Test email sent to ${testTo.trim()}.`
        : data.status === 'recorded_not_delivered'
          ? 'Test recorded, but the address is a demo address or no provider is configured.'
          : `No email delivered: ${data.reason ?? data.status ?? 'unknown reason'}.`)
    } catch (error) {
      setTestResult(error instanceof Error ? error.message : 'Test send failed.')
    } finally {
      setTestBusy(false)
    }
  }

  return (
    <main className="min-h-screen bg-slate-50 px-4 py-8 text-slate-900 sm:py-12">
      <div className="mx-auto max-w-5xl space-y-7">
        <header className="rounded-3xl bg-[#0f1b2d] p-7 text-white sm:p-9">
          <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-[0.2em] text-amber-300"><ShieldAlert size={17} /> HeavyHaul Agent · development demo</div>
          <h1 className="mt-4 text-3xl font-bold tracking-tight sm:text-4xl">Permit dimension alert</h1>
          <p className="mt-3 max-w-2xl text-sm leading-6 text-slate-300">Try a permit that is too small, run the check twice, then change the dimensions. This uses Workspace’s comparison and default alert email copy.</p>
          <p className="mt-5 inline-block rounded-lg border border-amber-400/40 bg-amber-300/10 px-3 py-2 text-xs font-medium text-amber-200">Sample trip · no trip data is changed · test emails go only to the address you enter below</p>
        </header>

        <div className="grid gap-4 lg:grid-cols-2">
          <DimCard title="Trip overall dimensions" dimensions={DEMO_TRIP_DIMENSIONS} />
          <DimCard title="Georgia permit allowance" dimensions={permitDimensions} editable onChange={(key, value) => changePermit({ ...permitDimensions, [key]: value })} />
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <button className="rounded-lg bg-[#0f1b2d] px-4 py-2.5 text-sm font-semibold text-white hover:bg-[#1f3350]" onClick={runCheck}>Run alert check</button>
          <button className="rounded-lg border border-slate-300 bg-white px-3 py-2.5 text-sm font-semibold hover:bg-slate-100" onClick={() => changePermit(DEMO_SMALL_PERMIT)}>Too small</button>
          <button className="rounded-lg border border-slate-300 bg-white px-3 py-2.5 text-sm font-semibold hover:bg-slate-100" onClick={() => changePermit(DEMO_MATCHING_PERMIT)}>Matching permit</button>
          <button className="inline-flex items-center gap-1.5 rounded-lg px-3 py-2.5 text-sm font-semibold text-slate-600 hover:bg-slate-200" onClick={reset}><RotateCcw size={15} /> Reset demo</button>
        </div>

        <div className="grid gap-4 lg:grid-cols-[1.2fr_1fr]">
          <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
            <h2 className="text-lg font-bold">Comparison result</h2>
            <p className="mt-1 text-xs text-slate-500">Workspace compares each permit allowance with the truck and trailer’s overall dimensions.</p>
            {warnings.length ? (
              <ul className="mt-4 space-y-2">{warnings.map((warning) => <li key={warning.message} className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">{warning.message}</li>)}</ul>
            ) : (
              <div className="mt-4 flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-3 py-3 text-sm font-medium text-green-800"><CheckCircle2 size={18} /> No dimensional mismatch found.</div>
            )}
          </section>
          <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
            <h2 className="text-lg font-bold">Simulated delivery</h2>
            <p className="mt-1 text-xs text-slate-500">Eligible trip contacts: active or invited broker and carrier dispatcher.</p>
            <div className="mt-4 space-y-2 text-sm">
              <div className="flex items-center justify-between rounded-lg bg-slate-100 px-3 py-2"><span>broker@example.com</span><span className="font-semibold">Broker</span></div>
              <div className="flex items-center justify-between rounded-lg bg-slate-100 px-3 py-2"><span>dispatch@example.com</span><span className="font-semibold">Dispatcher</span></div>
            </div>
            <div aria-live="polite" className={`mt-4 rounded-lg border px-3 py-3 text-sm ${!dimensionsChanged && latest?.outcome === 'sent' ? 'border-amber-300 bg-amber-50 text-amber-900' : !dimensionsChanged && latest?.outcome === 'clear' ? 'border-green-200 bg-green-50 text-green-800' : 'border-slate-200 bg-slate-50 text-slate-700'}`}>
              {dimensionsChanged ? 'Permit dimensions changed. Run the check to see the new outcome.' : latest?.details ?? 'Run the check to see whether an alert would be sent.'}
            </div>
            {runs.length > 1 && <ol className="mt-3 space-y-1 text-xs text-slate-500">{runs.slice(1).map((run) => <li key={run.id}>{run.details}</li>)}</ol>}
          </section>
        </div>

        <section className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center gap-2"><Mail size={19} className="text-amber-600" /><h2 className="text-lg font-bold">Email preview</h2></div>
          <p className="mt-1 text-xs text-slate-500">Default template shown for the broker. Saved template edits may change a live test email. Each real recipient gets a link to their own trip workspace.</p>
          <div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
            <div className="text-xs text-slate-500">To: broker@example.com</div>
            <div className="mt-2 border-b border-slate-200 pb-3 text-sm font-bold">{subject}</div>
            <pre className="mt-3 whitespace-pre-wrap break-words font-sans text-sm leading-6 text-slate-800">{warnings.length ? body : 'No dimensional mismatch. Workspace does not send this email.'}</pre>
          </div>
        </section>

        <section className="rounded-2xl border border-amber-200 bg-amber-50 p-5">
          <h2 className="text-lg font-bold">Send yourself a test email</h2>
          <p className="mt-1 max-w-2xl text-sm text-slate-600">Sign in with email-template admin access, enter your address, then send. This goes through the saved alert template, email policy, and configured provider. The subject is marked <strong>[DEMO TEST]</strong>; it does not create a permit or delivery reservation.</p>
          <div className="mt-4 flex flex-wrap gap-2">
            <input aria-label="Test email address" className="min-w-56 flex-1 rounded-lg border border-slate-300 bg-white px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-amber-400" type="email" placeholder="you@company.com" value={testTo} onChange={(event) => setTestTo(event.target.value)} />
            <button className="rounded-lg bg-[#0f1b2d] px-4 py-2.5 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-50" disabled={testBusy || !testTo.trim() || !warnings.length} onClick={sendTest}>{testBusy ? 'Sending…' : 'Send test email'}</button>
          </div>
          <p aria-live="polite" className="mt-3 text-sm font-medium text-slate-700">{testResult || (warnings.length ? 'The test email will use the current mismatch rows.' : 'Set a permit dimension below the trip requirement to enable the test send.')}</p>
        </section>

        <p className="flex items-start gap-2 px-1 text-xs leading-5 text-slate-500"><ArrowRight size={15} className="mt-0.5 shrink-0" /> In the live workflow, processed permit uploads and dimension edits run this check. A changed mismatch can send a new alert; a retry of the same mismatch is deduplicated per recipient.</p>
      </div>
    </main>
  )
}
