import { useState, useSyncExternalStore, type FormEvent } from 'react'
import { useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { CircleAlert, CircleCheck, CircleDashed, CircleX, FlaskConical, LoaderCircle, PhoneCall, Save } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { CopyButton } from '@/components/ApiCodeSamples'
import { ReadyCard, Section, SettingField, type SettingFieldState } from '@/components/admin/SettingsUi'
import { checkVoiceConnection, updateVoiceSettings } from '@/lib/admin.functions'
import { VOICE_FIELDS, type VoiceFieldKey } from '@/lib/voice'
import { cn } from '@/lib/utils'

type Check = Awaited<ReturnType<typeof checkVoiceConnection>>

const STATE_STYLE = {
  ok: { icon: CircleCheck, className: 'text-primary' },
  warn: { icon: CircleAlert, className: 'text-[oklch(0.55_0.13_70)]' },
  fail: { icon: CircleX, className: 'text-destructive' },
  skipped: { icon: CircleDashed, className: 'text-muted-foreground' },
} as const

// Africa's Talking credentials for Voice SMS on /admin/settings. A separate
// form from the Moolre one, saved on its own.
export function VoiceSettings({ fields }: { fields: SettingFieldState[] }) {
  const router = useRouter()
  const save = useServerFn(updateVoiceSettings)
  const runCheck = useServerFn(checkVoiceConnection)
  const [values, setValues] = useState<Partial<Record<VoiceFieldKey, string>>>(() =>
    Object.fromEntries(fields.map((f) => [f.key, f.value])),
  )
  const [clear, setClear] = useState<VoiceFieldKey[]>([])
  const [saving, setSaving] = useState(false)
  const [checking, setChecking] = useState(false)
  const [check, setCheck] = useState<Check | null>(null)

  const byKey = Object.fromEntries(fields.map((f) => [f.key, f])) as Record<VoiceFieldKey, SettingFieldState>
  const ready = VOICE_FIELDS.every((f) => !clear.includes(f.key) && (Boolean(values[f.key]?.trim()) || byKey[f.key].source !== 'none'))
  const changed = Object.fromEntries(
    VOICE_FIELDS.filter((f) => {
      const value = values[f.key]?.trim() ?? ''
      return value && value !== byKey[f.key].value
    }).map((f) => [f.key, values[f.key]!.trim()]),
  ) as Partial<Record<VoiceFieldKey, string>>

  async function test() {
    setChecking(true)
    try {
      setCheck(await runCheck({ data: { values: changed, clear } }))
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'The check could not run.')
    } finally {
      setChecking(false)
    }
  }

  async function handleSubmit(event: FormEvent) {
    event.preventDefault()
    setSaving(true)
    try {
      await save({ data: { values: changed, clear } })
      toast.success('Voice settings saved.')
      setClear([])
      setValues((v) => {
        const next = { ...v }
        for (const f of VOICE_FIELDS) if (f.secret) next[f.key] = ''
        return next
      })
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Your settings could not be saved.')
      return
    } finally {
      setSaving(false)
    }
    await test()
  }

  const busy = saving || checking
  const style = check ? STATE_STYLE[check.state] : null

  return (
    <form onSubmit={handleSubmit} className="mt-14">
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          <p className="text-xs font-semibold tracking-[0.18em] text-primary uppercase">Voice SMS</p>
          <h2 className="mt-1 text-2xl font-bold">Africa’s Talking</h2>
          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            Voice SMS calls each recipient and reads the customer’s message aloud. Calls are placed by Africa’s Talking,
            since Moolre has no voice API. Customers pay 5 credits per number, refunded if the call isn’t answered.
          </p>
        </div>
        <ReadyCard icon={PhoneCall} title="Voice calls" ready={ready}>
          {ready ? 'All voice fields are filled in.' : 'Add the username, API key and number.'}
        </ReadyCard>
      </div>

      <Section
        icon={PhoneCall}
        title="Credentials"
        description="From your app on account.africastalking.com. The voice number must be a voice-enabled number on the same app."
      >
        {VOICE_FIELDS.map((meta) => (
          <SettingField
            key={meta.key}
            meta={meta}
            idPrefix="voice"
            field={byKey[meta.key]}
            value={values[meta.key] ?? ''}
            onChange={(value) => setValues((v) => ({ ...v, [meta.key]: value }))}
            cleared={clear.includes(meta.key)}
            onToggleClear={() => {
              setClear((c) => (c.includes(meta.key) ? c.filter((k) => k !== meta.key) : [...c, meta.key]))
              setValues((v) => ({ ...v, [meta.key]: byKey[meta.key].value }))
            }}
            disabled={saving}
          />
        ))}
        <CallbackUrl />
        {check && style && (
          <p className={cn('flex items-start gap-2 rounded-xl border bg-background/60 p-3 text-sm', style.className)} aria-live="polite">
            <style.icon className="mt-0.5 size-4 shrink-0" aria-hidden />
            <span className="text-foreground">{check.message}</span>
          </p>
        )}
      </Section>

      <div className="mt-6 flex flex-wrap items-center justify-end gap-3">
        <Button type="button" variant="outline" onClick={test} disabled={busy}>
          {checking ? <LoaderCircle className="animate-spin" /> : <FlaskConical />} Check connection
        </Button>
        <Button type="submit" disabled={busy}>
          <Save /> {saving ? 'Saving…' : 'Save voice settings'}
        </Button>
      </div>
    </form>
  )
}

function CallbackUrl() {
  const origin = useSyncExternalStore(
    () => () => {},
    () => window.location.origin,
    () => '',
  )
  const url = `${origin}/api/voice/callback`
  return (
    <div className="space-y-1.5">
      <Label>Voice callback URL</Label>
      <div className="flex items-center gap-2">
        <code className="min-w-0 flex-1 truncate rounded-md border bg-secondary/50 px-3 py-2 text-sm">{url}</code>
        <CopyButton value={url} />
      </div>
      <p className="text-xs text-muted-foreground">
        On Africa’s Talking, open Voice → Phone numbers, edit the voice number and paste this as its callback URL. It
        tells the call what to read out.
      </p>
    </div>
  )
}
