'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { BackLink } from '@/components/app/back-link'
import { LEAD_STAGE_LABELS, type LeadKind, type SegmentFilters } from '@/lib/domain/broker-leads'
import type { BrokerageRollup, LeadCampaign, LeadSegment, LeadTemplate, LeadsAnalytics, LeadsPage, LeadsSettings, LeadsSummary } from '@/lib/data/broker-leads'
import { BTN, BTN_SOFT, Stat, call } from './shared'
import { LeadsTab } from './leads-tab'
import { BrokeragesTab } from './brokerages-tab'
import { CampaignsTab } from './campaigns-tab'
import { AnalyticsTab } from './analytics-tab'
import { SettingsTab } from './settings-tab'
import { TemplatesTab } from './templates-tab'
import { LeadKindProvider, useLeadKind } from './kind-context'

/**
 * Freight Broker Leads manager (Nash, 2026-09-23) — the internal tool that
 * turns pre-verified leads into users: Leads · Brokerages · Campaigns ·
 * Templates · Analytics · Settings. Every action calls an admin route that
 * writes the lead's timeline.
 */
export interface ManagerProps {
  kind?: LeadKind
  available: boolean
  states: string[]
  tab?: string
  filters?: SegmentFilters
  sort?: 'activity' | 'name' | 'brokerage'
  leads?: LeadsPage
  summary?: LeadsSummary
  filteredSummary?: LeadsSummary
  rollups?: BrokerageRollup[]
  settings?: LeadsSettings
  segments?: LeadSegment[]
  templates?: LeadTemplate[]
  campaigns?: LeadCampaign[]
  analytics?: LeadsAnalytics | null
  me?: { email: string; name: string }
}

const TABS = (companyNoun: string): Array<[string, string]> => [['leads', 'Leads'], ['brokerages', companyNoun === 'brokerage' ? 'Brokerages' : 'Companies'], ['campaigns', 'Campaigns'], ['templates', 'Templates'], ['analytics', 'Analytics'], ['settings', 'Settings']]

export function BrokerLeadsManager(props: ManagerProps) {
  return <LeadKindProvider kind={props.kind ?? 'broker'}><ManagerBody {...props} /></LeadKindProvider>
}

function ManagerBody(props: ManagerProps) {
  const cfg = useLeadKind()
  const router = useRouter()
  const tab = props.tab ?? 'leads'
  const go = (t: string) => router.push(`${cfg.path}?tab=${t}`)

  if (!props.available) {
    const carrier = cfg.kind === 'carrier'
    return (
      <div className="mx-auto max-w-6xl space-y-6 px-4 py-8">
        <BackLink />
        <h1 className="text-2xl font-bold">{cfg.label}</h1>
        <div className="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
          <p className="font-semibold">Migration {carrier ? '0039' : '0030'} is not applied.</p>
          <p className="mt-1">Run <code className="rounded bg-white px-1">supabase/migrations/{carrier ? '0039_carrier_leads.sql' : '0030_broker_leads_campaigns.sql'}</code> in the Supabase SQL editor, then <code className="rounded bg-white px-1">node scripts/verify-migration-{carrier ? '0039' : '0030'}.mjs</code>.{carrier ? '' : ' Leads imported before that get their management columns from '}{carrier ? null : <code className="rounded bg-white px-1">node scripts/backfill-broker-lead-fields.mjs</code>}{carrier ? '' : '.'}</p>
        </div>
      </div>
    )
  }
  const s = props.summary!
  return (
    <div className="mx-auto max-w-7xl space-y-5 px-4 py-8">
      <BackLink />
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold">{cfg.label}</h1>
          <p className="mt-1 text-sm text-neutral-500">{cfg.kind === 'carrier' ? 'Dispatchers and drivers who used Synchron Permits without a carrier relationship. Invite them, run campaigns, watch who creates an account. Internal only.' : 'Pre-verified freight brokers and the brokerage they work for. Invite them, run campaigns, watch who signs up and confirms. Internal only — nothing here touches carriers.'}</p>
        </div>
        <CronSwitch settings={props.settings!} />
      </div>

      <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-8">
        <Stat label="Leads" value={s.total} sub={`${s.brokerages} ${cfg.companyNoun === 'brokerage' ? 'brokerages' : 'companies'}`} />
        <Stat label={LEAD_STAGE_LABELS.not_invited} value={s.stages.not_invited} />
        <Stat label="Invited" value={s.stages.invited + s.stages.opened + s.stages.clicked} sub={`${s.stages.opened + s.stages.clicked} opened · ${s.stages.clicked} clicked`} />
        <Stat label="Signed up" value={s.stages.signed_up} />
        <Stat label={cfg.convertedLabel} value={s.stages.converted} sub={s.total ? `${((s.stages.converted / s.total) * 100).toFixed(1)}% of leads` : undefined} />
        <Stat label="Declined" value={s.stages.declined} />
        <Stat label="Bounced / unsubscribed" value={s.stages.bounced + s.stages.unsubscribed + s.stages.suppressed} />
        <Stat label="Manual review" value={s.stages.manual_review} />
      </div>

      <nav className="flex gap-1 overflow-x-auto border-b">
        {TABS(cfg.companyNoun).map(([key, label]) => (
          <button key={key} onClick={() => go(key)} className={`shrink-0 border-b-2 px-3 py-2 text-sm font-semibold ${tab === key ? 'border-[#0f1b2d] text-[#0f1b2d]' : 'border-transparent text-neutral-500 hover:text-neutral-900'}`}>
            {label}
            {key === 'campaigns' && props.campaigns!.some((c) => c.status === 'running') && <span className="ml-1.5 rounded-full bg-green-100 px-1.5 text-[10px] text-green-800">running</span>}
            {key === 'leads' && s.stages.manual_review > 0 && <span className="ml-1.5 rounded-full bg-amber-100 px-1.5 text-[10px] text-amber-800">{s.stages.manual_review} to review</span>}
          </button>
        ))}
      </nav>

      {tab === 'leads' && <LeadsTab leads={props.leads!} filters={props.filters!} sort={props.sort!} filteredSummary={props.filteredSummary!} summary={s} states={props.states} segments={props.segments!} templates={props.templates!} rollups={props.rollups!} />}
      {tab === 'brokerages' && <BrokeragesTab rollups={props.rollups!} />}
      {tab === 'campaigns' && <CampaignsTab campaigns={props.campaigns!} templates={props.templates!} segments={props.segments!} settings={props.settings!} states={props.states} me={props.me!} />}
      {tab === 'templates' && <TemplatesTab leads={props.leads!.rows} />}
      {tab === 'analytics' && props.analytics && <AnalyticsTab analytics={props.analytics} />}
      {tab === 'settings' && <SettingsTab settings={props.settings!} templates={props.templates!} />}
    </div>
  )
}

function CronSwitch({ settings }: { settings: LeadsSettings }) {
  const cfg = useLeadKind()
  const router = useRouter()
  const [busy, setBusy] = useState(false)
  async function toggle() {
    setBusy(true)
    try {
      await call(`${cfg.apiBase}/settings`, { cron_enabled: !settings.cron_enabled })
      toast.success(settings.cron_enabled ? 'Automatic sending switched off. Campaigns keep their place; nothing goes out until it is on again.' : 'Automatic sending switched on. Running campaigns send on the hourly schedule, inside their windows and limits.')
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Could not change the switch.') } finally { setBusy(false) }
  }
  async function runNow() {
    setBusy(true)
    try {
      const r = await call<{ summary: { ran: boolean; reason?: string; campaigns: Array<{ name: string; sent: number; rescheduled: number; stopped: number; skipped: number; failed: number }> } }>(`${cfg.apiBase}/campaigns`, { op: 'run_now' })
      const lines = r.summary.campaigns.map((c) => `${c.name}: ${c.sent} sent, ${c.rescheduled} waiting for a window, ${c.stopped} stopped, ${c.skipped} skipped${c.failed ? `, ${c.failed} failed` : ''}`)
      toast.success(lines.length ? lines.join(' · ') : 'No running campaign had anything due.')
      router.refresh()
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Run failed.') } finally { setBusy(false) }
  }
  return (
    <div className="flex items-center gap-2 rounded-xl border bg-white px-3 py-2 text-xs">
      <span className={`h-2.5 w-2.5 rounded-full ${settings.cron_enabled ? 'bg-green-500' : 'bg-neutral-300'}`} />
      <span className="font-semibold">Automatic sending {settings.cron_enabled ? 'on' : 'off'}</span>
      <button onClick={toggle} disabled={busy} className={BTN_SOFT}>{settings.cron_enabled ? 'Switch off' : 'Switch on'}</button>
      <button onClick={runNow} disabled={busy} className={BTN} title="Execute one scheduler pass now, regardless of the switch">Run now</button>
    </div>
  )
}
