import { useState } from 'react'
import { useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { ListChecks, LoaderCircle, Save } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { ReadyCard, Section } from '@/components/admin/SettingsUi'
import { getDeliverySettings, updateDeliveryLabels } from '@/lib/admin.functions'
import { DELIVERY_LABELS, type DeliveryLabel } from '@/lib/delivery'

type Data = Awaited<ReturnType<typeof getDeliverySettings>>

// Labels for Moolre's per-message delivery numbers. Moolre doesn't publish
// what each number means, so customers see "Sent" for a number until it has a
// label here.
export function DeliverySettings({ data }: { data: Data }) {
  const router = useRouter()
  const save = useServerFn(updateDeliveryLabels)
  const initial = Object.fromEntries(data.codes.map((c) => [c.code, c.label])) as Record<number, DeliveryLabel | null>
  const [labels, setLabels] = useState(initial)
  const [saving, setSaving] = useState(false)
  const changed = data.codes.some((c) => labels[c.code] !== c.label)
  const seenUnlabelled = data.codes.filter((c) => c.seen > 0 && !labels[c.code])
  const labelled = data.codes.filter((c) => labels[c.code]).length

  async function onSave() {
    setSaving(true)
    try {
      await save({ data: { labels: Object.fromEntries(data.codes.map((c) => [String(c.code), labels[c.code] ?? null])) } })
      toast.success('Delivery labels saved')
      await router.invalidate()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Could not save the labels.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div 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">Delivery reports</p>
          <h2 className="mt-1 text-2xl font-bold">Per-number delivery</h2>
          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            Moolre reports each message’s delivery as a number but doesn’t publish what the numbers mean. Label each number
            here once. Until a number has a label, customers see those messages as “Sent” (accepted by Moolre), never as
            delivered or failed.
          </p>
        </div>
        <ReadyCard icon={ListChecks} title="Delivery labels" ready={seenUnlabelled.length === 0 && labelled > 0}>
          {seenUnlabelled.length > 0
            ? `${seenUnlabelled.length} number${seenUnlabelled.length === 1 ? '' : 's'} came back without a label.`
            : labelled > 0
              ? `${labelled} labelled.`
              : 'No numbers seen yet.'}
        </ReadyCard>
      </div>

      <Section
        icon={ListChecks}
        title="Moolre status numbers"
        description="To work out a number: send a test to your own phone (should be Delivered) and to a switched-off phone, then compare. Or ask Moolre support what each SMS status number means."
      >
        <div className="grid gap-2">
          {data.codes.map((c) => (
            <div key={c.code} className="flex flex-wrap items-center gap-3 rounded-xl border bg-background/60 px-3 py-2">
              <span className="w-28 font-mono text-sm">Status {c.code}</span>
              <span className="w-40 text-xs text-muted-foreground tabular-nums">
                {c.seen > 0 ? `${c.seen.toLocaleString()} messages, last 30 days` : 'Not seen yet'}
              </span>
              <label className="sr-only" htmlFor={`dlr-${c.code}`}>
                Meaning of status {c.code}
              </label>
              <select
                id={`dlr-${c.code}`}
                className="h-9 min-w-48 rounded-lg border bg-card px-3 text-sm"
                value={labels[c.code] ?? ''}
                onChange={(e) => setLabels({ ...labels, [c.code]: (e.target.value || null) as DeliveryLabel | null })}
              >
                <option value="">Not labelled (shown as Sent)</option>
                {DELIVERY_LABELS.map((l) => (
                  <option key={l.value} value={l.value}>
                    {l.label}: {l.hint}
                  </option>
                ))}
              </select>
            </div>
          ))}
          {data.unlisted.length > 0 && (
            <p className="text-xs text-muted-foreground">
              Moolre also returned {data.unlisted.map((u) => `status ${u.code} (${u.count})`).join(', ')}, which can’t be
              labelled yet.
            </p>
          )}
          <div>
            <Button onClick={onSave} disabled={!changed || saving}>
              {saving ? <LoaderCircle className="animate-spin" /> : <Save />}
              Save labels
            </Button>
          </div>
        </div>
      </Section>
    </div>
  )
}
