import { useEffect, useRef, useState, type FormEvent } from 'react'
import { Link, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { CheckCircle2, Info, ListChecks, PhoneCall, Play, Square, TriangleAlert, X } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Textarea } from '@/components/ui/textarea'
import { FieldLabel, RecipientsField, useRecipients } from '@/components/RecipientsField'
import { SectionHeading } from '@/components/SmsComposer'
import { sendVoiceSms } from '@/lib/voice.functions'
import { MAX_VOICE_CHARS, MAX_VOICE_RECIPIENTS, VOICES, VOICE_CREDITS_PER_RECIPIENT, estimateSpeechSeconds, voiceLabel, type Voice } from '@/lib/voice'
import { cn } from '@/lib/utils'

type SendResult = { status: string; placed: number; total: number; creditsUsed: number }

export function VoiceComposer({ credits, available }: { credits: number; available: boolean }) {
  const router = useRouter()
  const send = useServerFn(sendVoiceSms)
  const recipientState = useRecipients()
  const { parsed } = recipientState
  const [voice, setVoice] = useState<Voice>('woman')
  const [message, setMessage] = useState('')
  const [pending, setPending] = useState(false)
  const [confirming, setConfirming] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [lastResult, setLastResult] = useState<SendResult | null>(null)

  const seconds = estimateSpeechSeconds(message)
  const cost = parsed.valid.length * VOICE_CREDITS_PER_RECIPIENT
  const tooLong = message.length > MAX_VOICE_CHARS
  const tooMany = parsed.valid.length > MAX_VOICE_RECIPIENTS
  const insufficient = cost > credits
  const canSend = available && parsed.valid.length > 0 && message.trim().length > 0 && !tooLong && !tooMany && !insufficient && !pending

  function review(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!canSend) return
    setError(null)
    setConfirming(true)
  }

  async function submit() {
    setPending(true)
    setError(null)
    try {
      const result = await send({ data: { message, voice, recipients: parsed.valid.join('\n') } })
      if (result.status === 'partial') {
        toast.warning(`Calling ${result.placed} of ${result.total} numbers. Credits for the rest were refunded.`)
      } else {
        toast.success(`Calling ${result.placed.toLocaleString()} number${result.placed === 1 ? '' : 's'} now.`)
      }
      setLastResult(result)
      recipientState.reset()
      setMessage('')
      await router.invalidate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Your voice message could not be sent.')
    } finally {
      setPending(false)
      setConfirming(false)
    }
  }

  return (
    <div className="grid gap-6 lg:grid-cols-[1.35fr_0.65fr] lg:items-start">
      <form
        onSubmit={review}
        className="gradient-border grid gap-7 rounded-[1.75rem] bg-card p-6 shadow-deep [--ring-from:color-mix(in_oklch,var(--gold-glow)_70%,transparent)] [--ring-to:color-mix(in_oklch,var(--primary)_50%,transparent)] sm:p-8"
      >
        <div className="flex items-center justify-between gap-4">
          <SectionHeading eyebrow="Compose" title="New voice message" />
          <span className="hidden items-center gap-1.5 rounded-full bg-primary/10 px-3 py-1 text-xs font-semibold text-primary sm:inline-flex">
            <PhoneCall className="size-3.5" aria-hidden /> Read aloud by phone call
          </span>
        </div>

        {!available && (
          <div role="status" className="flex items-start gap-3 rounded-2xl border border-[var(--gold-glow)]/50 bg-[var(--gold-glow)]/15 px-4 py-3 text-sm">
            <TriangleAlert className="mt-0.5 size-5 shrink-0 text-[oklch(0.55_0.13_70)]" aria-hidden />
            <p>Voice SMS is being set up and can’t send calls just yet. You can still write and preview your message.</p>
          </div>
        )}

        {lastResult && (
          <div role="status" className="flex items-start gap-3 rounded-2xl border border-primary/25 bg-primary/5 px-4 py-3 text-sm">
            <CheckCircle2 className="mt-0.5 size-5 shrink-0 text-primary" aria-hidden />
            <p className="flex-1">
              <strong>
                Calling {lastResult.placed.toLocaleString()} of {lastResult.total.toLocaleString()} number
                {lastResult.total === 1 ? '' : 's'}
              </strong>{' '}
              · {lastResult.creditsUsed.toLocaleString()} credits used. Calls that aren’t answered are refunded
              automatically.{' '}
              <Link to="/dashboard" hash="history-heading" className="font-medium underline underline-offset-4">
                View history
              </Link>
            </p>
            <button
              type="button"
              onClick={() => setLastResult(null)}
              aria-label="Dismiss"
              className="rounded-full p-1 text-muted-foreground outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
            >
              <X className="size-4" aria-hidden />
            </button>
          </div>
        )}

        <fieldset disabled={pending} className="grid gap-7">
          <legend className="sr-only">New voice message</legend>

          <div className="grid gap-3">
            <FieldLabel step={1} htmlFor="voice-woman">
              Voice
            </FieldLabel>
            <div role="radiogroup" aria-label="Voice" className="grid gap-3 sm:grid-cols-2">
              {VOICES.map((option) => (
                <button
                  key={option.value}
                  id={`voice-${option.value}`}
                  type="button"
                  role="radio"
                  aria-checked={voice === option.value}
                  onClick={() => setVoice(option.value)}
                  className={cn(
                    'flex items-center gap-3 rounded-2xl border p-4 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring',
                    voice === option.value ? 'border-primary bg-primary/5 ring-1 ring-primary' : 'hover:bg-muted/50',
                  )}
                >
                  <span
                    className={cn(
                      'grid size-10 shrink-0 place-items-center rounded-full font-display text-sm font-bold',
                      voice === option.value ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground',
                    )}
                    aria-hidden
                  >
                    {option.label[0]}
                  </span>
                  <span>
                    <span className="block font-semibold">{option.label}</span>
                    <span className="block text-xs text-muted-foreground">{option.description}</span>
                  </span>
                </button>
              ))}
            </div>
          </div>

          <RecipientsField state={recipientState} step={2} max={MAX_VOICE_RECIPIENTS} />

          <div className="grid gap-2">
            <div className="flex items-baseline justify-between">
              <FieldLabel step={3} htmlFor="voice-message">
                Message
              </FieldLabel>
              <span className={cn('text-xs tabular-nums', tooLong ? 'text-destructive' : 'text-muted-foreground')} aria-live="polite">
                {message.length} / {MAX_VOICE_CHARS} chars · about {seconds}s spoken
              </span>
            </div>
            <Textarea
              id="voice-message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={5}
              placeholder="Hello, this is Akoto Pharmacy. Your prescription is ready for pick-up. Thank you."
              aria-invalid={tooLong}
              aria-describedby="voice-message-hint"
              className="rounded-xl bg-muted/40 transition-colors focus-visible:bg-card"
              required
            />
            <div id="voice-message-hint" className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
              <span>
                {tooLong
                  ? `Voice messages can be at most ${MAX_VOICE_CHARS} characters (about 30 seconds).`
                  : 'Write it the way it should sound. Spell out numbers and short forms, e.g. “GH cedis 50” instead of “GH₵50”.'}
              </span>
              <SpeechPreview message={message} voice={voice} />
            </div>
          </div>
        </fieldset>

        <div className="stage grain relative flex flex-col gap-4 overflow-hidden rounded-2xl p-5 sm:flex-row sm:items-center sm:justify-between">
          <div className="aurora opacity-50" aria-hidden />
          <div className="relative z-10">
            <p className="text-sm text-white/60">This send costs</p>
            <p className="font-display text-3xl font-extrabold tabular-nums">
              <span className="text-gold">{cost.toLocaleString()}</span>{' '}
              <span className="text-base font-medium text-white/60">credit{cost === 1 ? '' : 's'}</span>
            </p>
            <p className="text-xs text-white/50 tabular-nums">
              {parsed.valid.length.toLocaleString()} number{parsed.valid.length === 1 ? '' : 's'} × {VOICE_CREDITS_PER_RECIPIENT}{' '}
              credits · {Math.max(0, credits - cost).toLocaleString()} left after
            </p>
            {insufficient && (
              <p className="mt-1 text-sm text-[oklch(0.8_0.14_35)]">
                You need {(cost - credits).toLocaleString()} more.{' '}
                <Link to="/buy" className="font-medium underline underline-offset-4">
                  Top up
                </Link>
              </p>
            )}
          </div>
          <button
            type="submit"
            disabled={!canSend}
            className="btn-gold relative z-10 inline-flex h-12 items-center justify-center gap-2 rounded-full px-7 font-bold outline-none focus-visible:ring-4 focus-visible:ring-white/40 disabled:pointer-events-none disabled:opacity-45 disabled:grayscale-[0.4]"
          >
            <ListChecks className="size-4" aria-hidden /> Review &amp; send
          </button>
        </div>

        {error && (
          <p role="alert" className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            {error}
          </p>
        )}
      </form>

      <aside className="grid gap-6 lg:sticky lg:top-24">
        <CallPreview message={message} voice={voice} recipients={parsed.valid.length} seconds={seconds} />
        <Tips />
      </aside>

      <Dialog open={confirming} onOpenChange={(open) => !pending && setConfirming(open)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Call these numbers?</DialogTitle>
            <DialogDescription>Calls start right away and can’t be recalled.</DialogDescription>
          </DialogHeader>
          <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-2 rounded-xl bg-muted/50 p-4 text-sm">
            <dt className="text-muted-foreground">Voice</dt>
            <dd className="font-semibold">{voiceLabel(voice)} · English</dd>
            <dt className="text-muted-foreground">To</dt>
            <dd className="font-semibold tabular-nums">
              {parsed.valid.length === 1 ? `+${parsed.valid[0]}` : `${parsed.valid.length.toLocaleString()} numbers`}
            </dd>
            <dt className="text-muted-foreground">Length</dt>
            <dd className="tabular-nums">About {seconds} seconds</dd>
            <dt className="text-muted-foreground">Cost</dt>
            <dd className="font-semibold tabular-nums">
              {cost.toLocaleString()} credits{' '}
              <span className="font-normal text-muted-foreground">({Math.max(0, credits - cost).toLocaleString()} left after)</span>
            </dd>
          </dl>
          <p className="line-clamp-4 rounded-xl border px-4 py-3 text-sm whitespace-pre-wrap break-words">{message}</p>
          <DialogFooter>
            <Button type="button" variant="ghost" onClick={() => setConfirming(false)} disabled={pending}>
              Back to edit
            </Button>
            <Button type="button" onClick={submit} disabled={pending}>
              <PhoneCall className="size-4" aria-hidden /> {pending ? 'Placing calls…' : 'Call now'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

// Reads the message with the browser's own speech engine. It is only a rough
// guide: the phone call uses Africa's Talking's voice, which sounds different.
function SpeechPreview({ message, voice }: { message: string; voice: Voice }) {
  const [speaking, setSpeaking] = useState(false)
  const [supported, setSupported] = useState(false)
  // Held so the browser doesn't garbage-collect it mid-speech and skip onend.
  const utterance = useRef<SpeechSynthesisUtterance | null>(null)

  useEffect(() => {
    setSupported(typeof window !== 'undefined' && 'speechSynthesis' in window)
    return () => {
      if ('speechSynthesis' in window) window.speechSynthesis.cancel()
    }
  }, [])

  if (!supported) return null

  function toggle() {
    const synth = window.speechSynthesis
    if (speaking) {
      synth.cancel()
      setSpeaking(false)
      return
    }
    const u = new SpeechSynthesisUtterance(message)
    u.lang = 'en-GB'
    const english = synth.getVoices().filter((v) => v.lang.startsWith('en'))
    const wanted = voice === 'man' ? /male|daniel|david|george|james|guy|fred|alex/i : /female|samantha|zira|susan|hazel|karen|victoria|moira/i
    const match = english.find((v) => wanted.test(v.name) && !(voice === 'man' && /female/i.test(v.name)))
    if (match) u.voice = match
    u.pitch = voice === 'man' ? 0.85 : 1.1
    u.onend = () => setSpeaking(false)
    u.onerror = () => setSpeaking(false)
    utterance.current = u
    synth.cancel()
    synth.speak(u)
    setSpeaking(true)
  }

  return (
    <Button type="button" variant="outline" size="sm" className="h-8 rounded-full" onClick={toggle} disabled={!message.trim()}>
      {speaking ? <Square className="size-3.5" aria-hidden /> : <Play className="size-3.5" aria-hidden />}
      {speaking ? 'Stop' : 'Listen'}
    </Button>
  )
}

function CallPreview({ message, voice, recipients, seconds }: { message: string; voice: Voice; recipients: number; seconds: number }) {
  return (
    <div className="stage grain relative overflow-hidden rounded-[1.75rem] p-5">
      <div className="aurora opacity-70" aria-hidden />
      <p className="relative z-10 mb-4 flex items-center justify-between text-xs font-semibold tracking-[0.18em] text-white/60 uppercase">
        Call preview
        <span className="inline-flex items-center gap-1.5 normal-case tracking-normal">
          <span className="pulse-dot size-1.5 rounded-full bg-[oklch(0.8_0.15_150)]" aria-hidden /> what recipients hear
        </span>
      </p>
      <div className="relative z-10 rounded-[1.6rem] bg-gradient-to-b from-white/25 via-white/5 to-white/15 p-[1.5px]">
        <div className="rounded-[1.55rem] bg-[oklch(0.98_0.01_85)] p-5 text-foreground">
          <div className="flex flex-col items-center gap-2 border-b pb-4 text-center">
            <span className="grid size-12 place-items-center rounded-full bg-gradient-to-br from-primary to-[oklch(0.5_0.12_165)] text-primary-foreground" aria-hidden>
              <PhoneCall className="size-5" />
            </span>
            <p className="text-sm font-bold">Incoming call</p>
            <p className="text-[11px] text-muted-foreground">
              {voiceLabel(voice)} voice · {seconds > 0 ? `about ${seconds}s` : 'no message yet'}
            </p>
            <div className="mt-1 flex h-6 items-end gap-[3px]" aria-hidden>
              {Array.from({ length: 24 }, (_, i) => (
                <span
                  key={i}
                  className={cn('w-1 rounded-full', message ? 'bg-primary/70' : 'bg-muted')}
                  style={{ height: `${message ? 25 + ((i * 37) % 75) : 20}%` }}
                />
              ))}
            </div>
          </div>
          <p
            className={cn(
              'mt-4 max-h-60 overflow-y-auto text-sm leading-relaxed break-words whitespace-pre-wrap',
              !message && 'text-muted-foreground italic',
            )}
          >
            {message ? `“${message}”` : 'Start typing and the words read on the call appear here.'}
          </p>
          <p className="mt-3 text-right text-[11px] text-muted-foreground tabular-nums">
            {recipients > 0 ? `Calling ${recipients.toLocaleString()} phone${recipients === 1 ? '' : 's'}` : 'No recipients yet'}
          </p>
        </div>
      </div>
    </div>
  )
}

function Tips() {
  const tips = [
    { title: `${VOICE_CREDITS_PER_RECIPIENT} credits per number.`, text: 'Each recipient gets a phone call and hears your message read aloud, up to about 30 seconds.' },
    { title: 'Missed calls are free.', text: 'If a call isn’t answered or can’t be placed, its credits go straight back to your balance.' },
    { title: 'Great for everyone.', text: 'Voice reaches people who don’t read texts often, like elderly customers or rural members.' },
    { title: 'Big lists', text: `can go out in one send of up to ${MAX_VOICE_RECIPIENTS.toLocaleString()} numbers. Calls are placed one after another, so large sends take a while.` },
  ]
  return (
    <div className="grid content-start gap-4 rounded-[1.75rem] border bg-card p-6 shadow-deep">
      <h2 className="flex items-center gap-2 text-lg font-bold">
        <Info className="size-5 text-primary" aria-hidden /> Good to know
      </h2>
      <ul className="grid gap-4 text-sm text-muted-foreground">
        {tips.map((tip, i) => (
          <li key={tip.title} className="grid grid-cols-[auto_1fr] gap-3">
            <span className="mt-0.5 font-display text-xs font-bold text-[oklch(0.6_0.14_70)]">0{i + 1}</span>
            <span>
              <strong className="text-foreground">{tip.title}</strong> {tip.text}
            </span>
          </li>
        ))}
      </ul>
    </div>
  )
}
