import { useState, type FormEvent } from 'react'
import { useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { CircleAlert, CircleCheck, CircleDashed, CircleX, FlaskConical, KeyRound, LoaderCircle, Mail, ReceiptText, Save, Send } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { EmptyState, StatusBadge, dateFormat, timeAgo } from '@/components/admin/AdminUi'
import { ReadyCard, Section, SettingField } from '@/components/admin/SettingsUi'
import { checkEmailConnection, getEmailSettings, sendTestReceipt, updateEmailReceipts, updateEmailSettings } from '@/lib/admin.functions'
import { EMAIL_FIELDS, type EmailFieldKey } from '@/lib/email'
import { cn } from '@/lib/utils'

type Data = Awaited<ReturnType<typeof getEmailSettings>>
type Check = Awaited<ReturnType<typeof checkEmailConnection>>

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

const KIND_LABEL: Record<string, string> = { receipt: 'Receipt', test: 'Test' }

// Emailed purchase receipts on /admin/settings: Gmail login, on/off, a test
// send and a log of the latest emails.
export function EmailSettings({ data }: { data: Data }) {
  const router = useRouter()
  const save = useServerFn(updateEmailSettings)
  const saveReceipts = useServerFn(updateEmailReceipts)
  const runCheck = useServerFn(checkEmailConnection)
  const sendTest = useServerFn(sendTestReceipt)
  const { fields } = data
  const [values, setValues] = useState<Partial<Record<EmailFieldKey, string>>>(() =>
    Object.fromEntries(fields.map((f) => [f.key, f.value])),
  )
  const [clear, setClear] = useState<EmailFieldKey[]>([])
  const [saving, setSaving] = useState(false)
  const [checking, setChecking] = useState(false)
  const [testing, setTesting] = useState(false)
  const [toggling, setToggling] = useState(false)
  const [testTo, setTestTo] = useState('')
  const [check, setCheck] = useState<Check | null>(null)

  const byKey = Object.fromEntries(fields.map((f) => [f.key, f])) as Record<EmailFieldKey, Data['fields'][number]>
  const changed = Object.fromEntries(
    EMAIL_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<EmailFieldKey, 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('Email settings saved.')
      setClear([])
      setValues((v) => {
        const next = { ...v }
        for (const f of EMAIL_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()
  }

  async function toggleReceipts(enabled: boolean) {
    setToggling(true)
    try {
      await saveReceipts({ data: { enabled } })
      toast.success(enabled ? 'Receipt emails switched on.' : 'Receipt emails switched off.')
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Your change could not be saved.')
    } finally {
      setToggling(false)
    }
  }

  async function sendTestEmail() {
    setTesting(true)
    try {
      await sendTest({ data: { values: changed, clear, to: testTo.trim() } })
      toast.success(`Sample receipt sent to ${testTo.trim()}.`)
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'The test email could not be sent.')
    } finally {
      setTesting(false)
    }
  }

  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">Email receipts</p>
          <h2 className="mt-1 text-2xl font-bold">Gmail</h2>
          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            When a credit purchase is confirmed, the customer gets a receipt at the email they sign in with. It is sent
            from {data.address}, so copies appear in that Gmail account’s Sent folder and customer replies land in its
            inbox.
          </p>
        </div>
        <ReadyCard icon={Mail} title="Receipts" ready={data.ready && data.receiptsEnabled}>
          {!data.ready ? 'Add the Gmail app password below.' : data.receiptsEnabled ? `Sending from ${data.address}` : 'Switched off'}
        </ReadyCard>
      </div>

      <Section icon={ReceiptText} title="Purchase receipts" description="Sent once per payment, after Moolre confirms it and the credits are added.">
        <label className="flex items-center justify-between gap-4 rounded-xl border bg-background/60 p-3 text-sm">
          <span className="font-medium">
            {data.receiptsEnabled ? 'On: customers receive a receipt by email' : 'Off: no receipt emails are sent'}
          </span>
          <Switch
            checked={data.receiptsEnabled}
            onCheckedChange={toggleReceipts}
            disabled={toggling}
            aria-label="Email a receipt for each credit purchase"
          />
        </label>
        <div className="flex flex-wrap items-end gap-2">
          <div className="grid gap-1.5">
            <Label htmlFor="email-test-to" className="text-xs">
              Send a sample receipt to
            </Label>
            <Input
              id="email-test-to"
              type="email"
              placeholder="you@example.com"
              value={testTo}
              onChange={(e) => setTestTo(e.target.value)}
              className="w-64"
            />
          </div>
          <Button type="button" variant="outline" onClick={sendTestEmail} disabled={testing || !testTo.trim()}>
            {testing ? <LoaderCircle className="animate-spin" /> : <Send />} Send test
          </Button>
        </div>
      </Section>

      <Section
        icon={KeyRound}
        title="Gmail login"
        description="Gmail only lets websites send mail with an app password. Turn on 2-Step Verification for the account, then create one at myaccount.google.com/apppasswords."
      >
        {EMAIL_FIELDS.map((meta) => (
          <SettingField
            key={meta.key}
            meta={meta}
            idPrefix="email"
            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}
          />
        ))}
        {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 email settings'}
        </Button>
      </div>

      <section className="mt-6 rounded-[1.5rem] border bg-card p-6 shadow-deep">
        <h3 className="text-lg font-bold">Latest emails</h3>
        {data.recent.length === 0 ? (
          <div className="mt-4">
            <EmptyState>No receipt emails have been sent yet.</EmptyState>
          </div>
        ) : (
          <ul className="mt-4 divide-y">
            {data.recent.map((m) => (
              <li key={m.id} className="grid gap-1 py-3 text-sm sm:grid-cols-[8rem_1fr_auto] sm:gap-4">
                <span className="font-medium">{KIND_LABEL[m.kind] ?? m.kind}</span>
                <span className="min-w-0">
                  <span className="block truncate">{m.toEmail}</span>
                  <span className="block truncate text-muted-foreground" title={m.error ?? m.subject}>
                    {m.error ?? m.subject}
                  </span>
                </span>
                <span className="flex items-center gap-3 sm:justify-end">
                  <StatusBadge status={m.status === 'sent' ? 'sent' : 'failed'} />
                  <time className="text-xs text-muted-foreground" dateTime={m.createdAt} title={dateFormat.format(new Date(m.createdAt))}>
                    {timeAgo(m.createdAt)}
                  </time>
                </span>
              </li>
            ))}
          </ul>
        )}
      </section>
    </form>
  )
}
