import { useState, useSyncExternalStore, type FormEvent, type ReactNode } from 'react'
import { createFileRoute, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import {
  CircleAlert,
  CircleCheck,
  CircleDashed,
  CircleX,
  CreditCard,
  ExternalLink,
  FlaskConical,
  KeyRound,
  LoaderCircle,
  MessageSquareText,
  Radio,
  RefreshCw,
  Save,
  TriangleAlert,
  type LucideIcon,
} from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { CopyButton } from '@/components/ApiCodeSamples'
import { PageIntro, filterBarClass, filterClass, timeAgo } from '@/components/admin/AdminUi'
import { ReadyCard, Section, SettingField } from '@/components/admin/SettingsUi'
import { VoiceSettings } from '@/components/admin/VoiceSettings'
import { AutoSmsSettings } from '@/components/admin/AutoSmsSettings'
import { EmailSettings } from '@/components/admin/EmailSettings'
import { DeliverySettings } from '@/components/admin/DeliverySettings'
import { checkMoolreConnection, getAutoSmsAdmin, getDeliverySettings, getEmailSettings, getMoolreSettings, getVoiceSettings, updateMoolreSettings } from '@/lib/admin.functions'
import {
  MOOLRE_FIELDS,
  decodeMoolreKey,
  moolreKeyProblem,
  walletMismatch,
  type MoolreEnvironment,
  type MoolreFieldKey,
} from '@/lib/moolre-settings'
import { SENDER_ID_PATTERN, normalizeSenderId } from '@/lib/sms'
import { cn } from '@/lib/utils'

export const Route = createFileRoute('/admin/settings')({
  loader: async () => {
    const [moolre, voice, autoSms, email, delivery] = await Promise.all([
      getMoolreSettings(),
      getVoiceSettings(),
      getAutoSmsAdmin(),
      getEmailSettings(),
      getDeliverySettings(),
    ])
    return { moolre, voice, autoSms, email, delivery }
  },
  head: () => ({ meta: [{ title: 'Admin · API settings — AkotoCreative SMS' }] }),
  pendingComponent: SettingsSkeleton,
  component: SettingsPage,
})

type Settings = Awaited<ReturnType<typeof getMoolreSettings>>
type Field = Settings['fields'][number]
type Connection = Awaited<ReturnType<typeof checkMoolreConnection>>
type CheckId = Connection['checks'][number]['id']

const PAYMENT_KEYS: MoolreFieldKey[] = ['apiUser', 'apiPubkey', 'accountNumber', 'businessEmail']
const SMS_KEYS: MoolreFieldKey[] = ['vasKey', 'senderId']

const CHECKS: { id: CheckId; label: string; icon: LucideIcon }[] = [
  { id: 'login', label: 'Payment login', icon: KeyRound },
  { id: 'checkout', label: 'Checkout link', icon: CreditCard },
  { id: 'sms', label: 'SMS key', icon: MessageSquareText },
  { id: 'sender', label: 'Default sender ID', icon: Radio },
]

function SettingsPage() {
  const { moolre: settings, voice, autoSms, email, delivery } = Route.useLoaderData()
  const router = useRouter()
  const save = useServerFn(updateMoolreSettings)
  const runCheck = useServerFn(checkMoolreConnection)
  const [environment, setEnvironment] = useState<MoolreEnvironment>(settings.environment.value)
  const [values, setValues] = useState<Partial<Record<MoolreFieldKey, string>>>(() =>
    Object.fromEntries(settings.fields.map((f) => [f.key, f.value])),
  )
  const [clear, setClear] = useState<MoolreFieldKey[]>([])
  const [saving, setSaving] = useState(false)
  const [checking, setChecking] = useState(false)
  const [connection, setConnection] = useState<(Connection & { unsaved: boolean }) | null>(null)

  const byKey = Object.fromEntries(settings.fields.map((f) => [f.key, f])) as Record<MoolreFieldKey, Field>
  const isSet = (key: MoolreFieldKey) =>
    !clear.includes(key) && (Boolean(values[key]?.trim()) || byKey[key].source !== 'none')
  const paymentsReady = PAYMENT_KEYS.every(isSet)
  const smsReady = isSet('vasKey')

  // Only what changed is sent. Blank secret fields keep their saved value.
  const changed = Object.fromEntries(
    MOOLRE_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<MoolreFieldKey, string>>
  const dirty = Object.keys(changed).length > 0 || clear.length > 0 || environment !== settings.environment.value

  const warnings = fieldWarnings(values, byKey, clear)

  // Sends the form's changes so unsaved values can be checked before saving.
  async function check(data: { environment: MoolreEnvironment; values: typeof changed; clear: MoolreFieldKey[] }, unsaved: boolean) {
    setChecking(true)
    try {
      const result = await runCheck({ data })
      setConnection({ ...result, unsaved })
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'The check could not run.')
    } finally {
      setChecking(false)
    }
  }

  async function handleSubmit(event: FormEvent) {
    event.preventDefault()
    const data = { environment, values: changed, clear }
    setSaving(true)
    try {
      await save({ data })
      toast.success('Moolre API settings saved. Checking the connection…')
      setClear([])
      setValues((v) => {
        const next = { ...v }
        for (const f of MOOLRE_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 check(data, false)
  }

  function toggleClear(key: MoolreFieldKey) {
    setClear((c) => (c.includes(key) ? c.filter((k) => k !== key) : [...c, key]))
    setValues((v) => ({ ...v, [key]: byKey[key].value }))
  }

  const renderFields = (keys: MoolreFieldKey[]) =>
    keys.map((key) => (
      <div key={key} className="grid gap-1.5">
        <SettingField
          meta={MOOLRE_FIELDS.find((f) => f.key === key)!}
          idPrefix="moolre"
          field={byKey[key]}
          value={values[key] ?? ''}
          onChange={(value) => setValues((v) => ({ ...v, [key]: value }))}
          cleared={clear.includes(key)}
          onToggleClear={() => toggleClear(key)}
          disabled={saving}
        />
        {warnings[key] && (
          <p className="flex items-start gap-1.5 text-xs font-medium text-[oklch(0.5_0.13_60)]">
            <TriangleAlert className="mt-px size-3.5 shrink-0" aria-hidden /> {warnings[key]}
          </p>
        )}
      </div>
    ))

  const busy = saving || checking

  return (
    <>
      <form onSubmit={handleSubmit}>
        <PageIntro
          eyebrow="Settings"
          title="Moolre API"
          actions={
            <>
              <Button type="button" variant="outline" onClick={() => check({ environment, values: changed, clear }, true)} disabled={busy}>
                {checking ? <LoaderCircle className="animate-spin" /> : <FlaskConical />} Check connection
              </Button>
              <Button type="submit" disabled={busy}>
                <Save /> {saving ? 'Saving…' : 'Save and check'}
              </Button>
            </>
          }
        >
          Paste your credentials from app.moolre.com, check them, then save. Saved values are used straight away and take
          priority over environment variables. Keys stay on the server and are never shown again in full.
        </PageIntro>

        <div className="mt-8 grid gap-3 sm:grid-cols-2">
          <ReadyCard icon={CreditCard} title="Payments" ready={paymentsReady}>
            {paymentsReady ? 'All payment fields are filled in.' : 'Add the username, public key, wallet and email.'}
          </ReadyCard>
          <ReadyCard icon={MessageSquareText} title="SMS sending" ready={smsReady}>
            {smsReady ? 'The VAS key is filled in.' : 'Add the VAS key to send SMS.'}
          </ReadyCard>
        </div>

        <ConnectionPanel connection={connection} checking={checking} dirty={dirty} onCheck={() => check({ environment, values: changed, clear }, true)} disabled={busy} />

        <Section
          icon={Radio}
          title="1 · Environment"
          description="Live and Sandbox are separate Moolre systems with their own accounts and keys."
        >
          <div className={cn(filterBarClass, 'flex')} role="radiogroup" aria-label="Moolre environment">
            {(['live', 'sandbox'] as const).map((env) => (
              <button
                key={env}
                type="button"
                role="radio"
                aria-checked={environment === env}
                onClick={() => setEnvironment(env)}
                className={filterClass(environment === env)}
                disabled={saving}
              >
                {env === 'live' ? <Radio className="size-4" aria-hidden /> : <FlaskConical className="size-4" aria-hidden />}
                {env === 'live' ? 'Live' : 'Sandbox'}
              </button>
            ))}
          </div>
          <p className="text-sm text-muted-foreground">
            {environment === 'live' ? (
              <>Real payments and messages. Use the keys from <MoolreLink href="https://app.moolre.com">app.moolre.com</MoolreLink>.</>
            ) : (
              <>Test mode. Only works with a separate account and keys from <MoolreLink href="https://sandbox.moolre.com">sandbox.moolre.com</MoolreLink>.</>
            )}
          </p>
        </Section>

        <Section
          icon={CreditCard}
          title="2 · Payments"
          description="Collections use your username (X-API-USER) and Public API key (X-API-PUBKEY). Copy both, plus the wallet account number, from the same API Service on Moolre."
        >
          {renderFields(PAYMENT_KEYS)}
        </Section>

        <Section
          icon={MessageSquareText}
          title="3 · SMS"
          description="The VAS key comes from the SMS section on Moolre. Sender IDs must be approved there first."
        >
          {renderFields(SMS_KEYS)}
        </Section>

        <Section icon={KeyRound} title="4 · Webhook" description="Moolre calls this site when a payment completes.">
          <WebhookUrl />
          {renderFields(['callbackSecret'])}
        </Section>

        <div className="mt-8 flex flex-wrap items-center justify-end gap-3">
          {dirty && <p className="text-sm text-muted-foreground">You have unsaved changes.</p>}
          <Button type="submit" disabled={busy}>
            <Save /> {saving ? 'Saving…' : 'Save and check'}
          </Button>
        </div>
      </form>
      <AutoSmsSettings data={autoSms} />
      <DeliverySettings data={delivery} />
      <EmailSettings data={email} />
      <VoiceSettings fields={voice.fields} />
    </>
  )
}

// Mistakes that can be spotted without asking Moolre: a key in the wrong
// field, a phone number instead of the wallet number, an invalid sender ID.
function fieldWarnings(
  values: Partial<Record<MoolreFieldKey, string>>,
  byKey: Record<MoolreFieldKey, Field>,
  clear: MoolreFieldKey[],
) {
  const current = (key: MoolreFieldKey) => (clear.includes(key) ? '' : (values[key]?.trim() ?? ''))
  const warnings: Partial<Record<MoolreFieldKey, string>> = {}

  for (const key of ['apiPubkey', 'vasKey'] as const) {
    const problem = moolreKeyProblem(key, current(key))
    if (problem) warnings[key] = problem
  }

  const pubkey = current('apiPubkey')
  const walletid = pubkey ? decodeMoolreKey(pubkey)?.walletid : clear.includes('apiPubkey') ? undefined : byKey.apiPubkey.keyInfo?.walletid
  const account = current('accountNumber')
  if (/^(\+?233|0)[235]\d{8}$/.test(account.replace(/\s/g, ''))) {
    warnings.accountNumber = 'This looks like a phone number. Use the wallet account number shown on your Moolre dashboard.'
  } else if (walletMismatch(account, walletid)) {
    warnings.accountNumber = `The public key is for wallet ${walletid}, but this number doesn't end with it. Check that both come from the same wallet.`
  }

  const sender = current('senderId')
  if (sender && !SENDER_ID_PATTERN.test(normalizeSenderId(sender))) {
    warnings.senderId = `“${sender}” is ${sender.length > 11 ? 'longer than 11 characters' : 'not valid'}. Moolre allows 3 to 11 letters, numbers or spaces. Change or remove it.`
  }
  return warnings
}

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

function ConnectionPanel({
  connection,
  checking,
  dirty,
  onCheck,
  disabled,
}: {
  connection: (Connection & { unsaved: boolean }) | null
  checking: boolean
  dirty: boolean
  onCheck: () => void
  disabled: boolean
}) {
  const results = new Map(connection?.checks.map((c) => [c.id, c]))
  const allOk = connection?.checks.every((c) => c.state === 'ok')
  return (
    <section className="mt-6 rounded-[1.5rem] border bg-card p-6 shadow-deep" aria-live="polite">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="grid gap-1">
          <h2 className="flex items-center gap-2 text-lg font-bold">
            <FlaskConical className="size-4 text-primary" aria-hidden /> Connection check
          </h2>
          <p className="text-sm text-muted-foreground">
            {connection ? (
              <>
                {allOk ? 'Everything works.' : 'Some checks need attention.'} Checked {connection.unsaved && dirty ? 'unsaved values' : 'saved values'} on{' '}
                {connection.environment === 'sandbox' ? 'Sandbox' : 'Live'}, {timeAgo(connection.checkedAt)}.
              </>
            ) : (
              'Asks Moolre whether these credentials work, including changes you have not saved. Nothing is charged and no SMS is sent.'
            )}
          </p>
        </div>
        <Button type="button" variant="outline" size="sm" onClick={onCheck} disabled={disabled}>
          {checking ? <LoaderCircle className="animate-spin" /> : <RefreshCw />} {connection ? 'Check again' : 'Check now'}
        </Button>
      </div>
      <ul className="mt-5 grid gap-2 sm:grid-cols-2">
        {CHECKS.map(({ id, label, icon }) => {
          const result = results.get(id)
          const style = result ? STATE_STYLE[result.state] : null
          return (
            <CheckRow
              key={id}
              icon={icon}
              label={label}
              status={
                checking ? (
                  <LoaderCircle className="size-4 animate-spin text-muted-foreground" aria-label="Checking" />
                ) : style ? (
                  <style.icon className={cn('size-4', style.className)} aria-label={style.label} />
                ) : (
                  <CircleDashed className="size-4 text-muted-foreground" aria-label="Not checked" />
                )
              }
            >
              {checking ? 'Checking…' : (result?.message ?? 'Not checked yet.')}
              {!checking && result?.code && <span className="ml-1 font-mono text-[0.7rem] opacity-60">{result.code}</span>}
            </CheckRow>
          )
        })}
      </ul>
    </section>
  )
}

function CheckRow({ icon: Icon, label, status, children }: { icon: LucideIcon; label: string; status: ReactNode; children: ReactNode }) {
  return (
    <li className="flex gap-3 rounded-xl border bg-background/60 p-3">
      <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-secondary text-muted-foreground">
        <Icon className="size-4" aria-hidden />
      </span>
      <div className="min-w-0 flex-1">
        <p className="flex items-center justify-between gap-2 text-sm font-semibold">
          {label} {status}
        </p>
        <p className="text-sm text-muted-foreground">{children}</p>
      </div>
    </li>
  )
}

function MoolreLink({ href, children }: { href: string; children: ReactNode }) {
  return (
    <a href={href} target="_blank" rel="noreferrer" className="inline-flex items-center gap-0.5 font-medium text-primary underline-offset-4 hover:underline">
      {children} <ExternalLink className="size-3" aria-hidden />
    </a>
  )
}

// Shown so it can be pasted into the "Callback URL" field on Moolre's dashboard.
function WebhookUrl() {
  const origin = useSyncExternalStore(
    () => () => {},
    () => window.location.origin,
    () => '',
  )
  const url = `${origin}/api/moolre/webhook`
  return (
    <div className="space-y-1.5">
      <Label>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">Paste this into Callback URL on your Moolre dashboard.</p>
    </div>
  )
}

function SettingsSkeleton() {
  return (
    <div aria-busy="true">
      <Skeleton className="h-10 w-72" />
      <div className="mt-8 grid gap-3 sm:grid-cols-2">
        <Skeleton className="h-20 rounded-2xl" />
        <Skeleton className="h-20 rounded-2xl" />
      </div>
      <Skeleton className="mt-6 h-48 rounded-[1.5rem]" />
      <Skeleton className="mt-6 h-64 rounded-[1.5rem]" />
      <Skeleton className="mt-6 h-48 rounded-[1.5rem]" />
    </div>
  )
}
