import { useMemo, useState, type FormEvent } from 'react'
import { Link, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { CheckCircle2, Info, ListChecks, Send, Signal, 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { FieldLabel, RecipientsField, useRecipients } from '@/components/RecipientsField'
import { sendBulkSms } from '@/lib/account.functions'
import { countSegments } from '@/lib/sms'
import { cn } from '@/lib/utils'

// Mirrors MAX_RECIPIENTS / MAX_SEGMENTS in messaging.server.ts.
const MAX_RECIPIENTS = 5_000
const MAX_SEGMENTS = 6

type SendResult = { status: string; delivered: number; total: number; creditsUsed: number; error?: string | null }

export function SmsComposer({
  credits,
  defaultSenderId,
  senderIds,
}: {
  credits: number
  defaultSenderId: string
  senderIds: string[]
}) {
  const router = useRouter()
  const send = useServerFn(sendBulkSms)
  const recipientState = useRecipients()
  const { parsed } = recipientState
  const [senderId, setSenderId] = useState(defaultSenderId)
  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 seg = useMemo(() => countSegments(message), [message])
  const cost = parsed.valid.length * seg.segments
  const senderValid = senderIds.includes(senderId)
  const tooLong = seg.segments > MAX_SEGMENTS
  const tooMany = parsed.valid.length > MAX_RECIPIENTS
  const insufficient = cost > credits
  const canSend =
    senderValid && parsed.valid.length > 0 && seg.segments > 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 {
      // Send the cleaned, de-duplicated list rather than the raw paste.
      const result = await send({
        data: { senderId: senderId.trim(), message, recipients: parsed.valid.join('\n') },
      })
      if (result.status === 'partial') {
        toast.warning(`Sent to ${result.delivered} of ${result.total} numbers. Unsent credits were refunded.`)
      } else {
        toast.success(`Message sent to ${result.delivered.toLocaleString()} number${result.delivered === 1 ? '' : 's'}.`)
      }
      setLastResult(result)
      recipientState.reset()
      setMessage('')
      await router.invalidate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Your message could not be sent.')
    } finally {
      setPending(false)
      setConfirming(false)
    }
  }

  const partsLeft = seg.segments === 0 ? seg.perSegment : seg.segments * seg.perSegment - seg.length
  const partFill = seg.length === 0 ? 0 : Math.min(100, ((seg.perSegment - partsLeft) / seg.perSegment) * 100)

  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 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">
            <Signal className="size-3.5" aria-hidden /> MTN · Telecel · AirtelTigo
          </span>
        </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>
                Sent to {lastResult.delivered.toLocaleString()} of {lastResult.total.toLocaleString()} number
                {lastResult.total === 1 ? '' : 's'}
              </strong>{' '}
              · {lastResult.creditsUsed.toLocaleString()} credit{lastResult.creditsUsed === 1 ? '' : 's'} used.
              {lastResult.status === 'partial' && ' Credits for unsent numbers went back to your balance.'}{' '}
              <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 message</legend>
          <div className="grid gap-2">
            <FieldLabel step={1} htmlFor="sender">
              Sender ID
            </FieldLabel>
            <Select value={senderId} onValueChange={setSenderId} disabled={senderIds.length === 0}>
              <SelectTrigger id="sender" className="h-11 w-full rounded-xl" aria-describedby="sender-hint">
                <SelectValue placeholder="No approved sender ID yet" />
              </SelectTrigger>
              <SelectContent>
                {senderIds.map((id) => (
                  <SelectItem key={id} value={id}>
                    {id}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p id="sender-hint" className="text-xs text-muted-foreground">
              The name recipients see.{' '}
              <Link
                to="/dashboard"
                hash="sender-ids"
                className={cn('underline underline-offset-4', senderIds.length === 0 && 'font-medium text-foreground')}
              >
                {senderIds.length === 0 ? 'Request a sender ID' : 'Request another'}
              </Link>{' '}
              — it can be used once an admin approves it.
            </p>
          </div>

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

          <div className="grid gap-2">
            <div className="flex items-baseline justify-between">
              <FieldLabel step={3} htmlFor="message">
                Message
              </FieldLabel>
              <span className="text-xs text-muted-foreground tabular-nums" aria-live="polite">
                {seg.length} chars · {seg.segments} SMS · {seg.encoding}
              </span>
            </div>
            <Textarea
              id="message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={5}
              placeholder="Type your message…"
              aria-invalid={tooLong}
              aria-describedby="message-meter"
              className="rounded-xl bg-muted/40 transition-colors focus-visible:bg-card"
              required
            />
            <div id="message-meter" className="flex items-center gap-3 text-xs text-muted-foreground">
              <div className="flex flex-1 gap-1" aria-hidden>
                {Array.from({ length: MAX_SEGMENTS }, (_, i) => (
                  <span key={i} className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
                    <span
                      className={cn(
                        'block h-full rounded-full transition-[width] duration-300',
                        tooLong ? 'bg-destructive' : 'bg-gradient-to-r from-primary to-[var(--gold-glow)]',
                      )}
                      style={{
                        width: i < seg.segments - 1 ? '100%' : i === seg.segments - 1 ? `${partFill}%` : '0%',
                      }}
                    />
                  </span>
                ))}
              </div>
              <span className="tabular-nums">
                {seg.length === 0 ? `${seg.perSegment} per part` : `${partsLeft} left in part`}
              </span>
            </div>
            {tooLong && <p className="text-xs text-destructive">Messages can be at most 6 SMS parts long.</p>}
          </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'} × {seg.segments} part
              {seg.segments === 1 ? '' : 's'} · {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">
        <MessagePreview senderId={senderId} message={message} recipients={parsed.valid.length} />
        <Tips />
      </aside>

      <Dialog open={confirming} onOpenChange={(open) => !pending && setConfirming(open)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Send this message?</DialogTitle>
            <DialogDescription>Messages go out 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">From</dt>
            <dd className="font-semibold">{senderId}</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">
              {seg.segments} SMS part{seg.segments === 1 ? '' : 's'} · {seg.encoding}
            </dd>
            <dt className="text-muted-foreground">Cost</dt>
            <dd className="font-semibold tabular-nums">
              {cost.toLocaleString()} credit{cost === 1 ? '' : 's'}{' '}
              <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}>
              <Send className="size-4" aria-hidden /> {pending ? 'Sending…' : 'Send now'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

function MessagePreview({ senderId, message, recipients }: { senderId: string; message: string; recipients: number }) {
  const name = senderId || 'Your brand'
  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">
        Live 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 /> as recipients see it
        </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-4 text-foreground">
          <div className="flex items-center gap-3 border-b pb-3">
            <span
              className="grid size-9 place-items-center rounded-full bg-gradient-to-br from-primary to-[oklch(0.5_0.12_165)] text-xs font-bold text-primary-foreground"
              aria-hidden
            >
              {name.slice(0, 2).toUpperCase()}
            </span>
            <div className="min-w-0">
              <p className="truncate text-sm font-bold">{name}</p>
              <p className="text-[11px] text-muted-foreground">Text message · now</p>
            </div>
          </div>
          <p
            className={cn(
              'mt-4 max-h-60 overflow-y-auto rounded-2xl rounded-tl-sm bg-white px-4 py-3 text-sm leading-relaxed break-words whitespace-pre-wrap shadow-sm ring-1 ring-black/5',
              !message && 'text-muted-foreground italic',
            )}
          >
            {message || 'Start typing and your message appears here.'}
          </p>
          <p className="mt-3 text-right text-[11px] text-muted-foreground tabular-nums">
            {recipients > 0
              ? `Going to ${recipients.toLocaleString()} phone${recipients === 1 ? '' : 's'}`
              : 'No recipients yet'}
          </p>
        </div>
      </div>
    </div>
  )
}

export function SectionHeading({ id, eyebrow, title }: { id?: string; eyebrow: string; title: string }) {
  return (
    <div>
      <p className="inline-flex items-center gap-2 font-display text-xs font-bold tracking-[0.22em] text-primary uppercase">
        <span className="h-px w-6 bg-gradient-to-r from-transparent to-primary" aria-hidden />
        {eyebrow}
      </p>
      <h2 id={id} className="mt-1 text-3xl font-extrabold">
        {title}
      </h2>
    </div>
  )
}

function Tips() {
  const tips = [
    {
      title: '1 credit = 1 SMS part to 1 number.',
      text: 'A part is 160 standard characters, or 153 each when a message spans several parts.',
    },
    {
      title: 'Emoji and special letters',
      text: 'switch the message to Unicode, which fits 70 characters per part.',
    },
    {
      title: 'Big lists',
      text: `can go out in one send of up to ${MAX_RECIPIENTS.toLocaleString()} numbers. Import a CSV and only the phone number cells are used.`,
    },
    {
      title: 'Nothing is wasted.',
      text: 'If a batch can’t be delivered to the network, its credits go straight back to your balance.',
    },
    {
      title: 'Sender IDs',
      text: 'are reviewed and registered with the networks before use. Approval usually takes one to two working days.',
    },
  ]
  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>
  )
}
