import { useRef, useState } from 'react'
import { useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { BellRing, CreditCard, LoaderCircle, LogIn, RotateCcw, 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 { Textarea } from '@/components/ui/textarea'
import { EmptyState, StatusBadge, dateFormat, timeAgo } from '@/components/admin/AdminUi'
import { ReadyCard, Section } from '@/components/admin/SettingsUi'
import { getAutoSmsAdmin, sendAutoSmsTest, updateAutoSms } from '@/lib/admin.functions'
import { AUTO_SMS_EVENTS, AUTO_SMS_MAX_LENGTH, renderAutoSms, sampleValues, type AutoSmsEvent } from '@/lib/auto-sms'
import { countSegments } from '@/lib/sms'

type Data = Awaited<ReturnType<typeof getAutoSmsAdmin>>

const ICONS = { sign_in: LogIn, purchase: CreditCard } as const
const EVENT_LABEL: Record<string, string> = { sign_in: 'Sign-in', purchase: 'Purchase', test: 'Test', login_code: 'App sign-in code' }

// Automatic texts to customers on /admin/settings: one card per event with
// its own save, plus a log of the latest texts.
export function AutoSmsSettings({ data }: { data: Data }) {
  const onCount = data.events.filter((e) => e.enabled).length
  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">Automatic messages</p>
          <h2 className="mt-1 text-2xl font-bold">Customer texts</h2>
          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            Texts sent automatically when a customer signs in or buys credit. They go out from your default sender ID
            {data.senderId ? <> (“{data.senderId}”)</> : null}, draw on the Moolre SMS balance and are never charged to
            the customer. Customers add their number under Settings → Text alerts.
          </p>
        </div>
        <ReadyCard icon={BellRing} title="Automatic texts" ready={Boolean(data.senderId) && onCount > 0}>
          {!data.senderId
            ? 'Set a default sender ID above first.'
            : `${onCount} of ${data.events.length} on · ${data.customersWithPhone.toLocaleString()} customers with a number`}
        </ReadyCard>
      </div>

      {data.events.map((event) => (
        <AutoSmsCard key={event.key} event={event} />
      ))}

      <section className="mt-6 rounded-[1.5rem] border bg-card p-6 shadow-deep">
        <h3 className="text-lg font-bold">Latest automatic texts</h3>
        {data.recent.length === 0 ? (
          <div className="mt-4">
            <EmptyState>No automatic texts 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">{EVENT_LABEL[m.event] ?? m.event}</span>
                <span className="min-w-0">
                  <span className="block truncate">
                    {m.email} · +{m.phone}
                  </span>
                  <span className="block truncate text-muted-foreground" title={m.message}>
                    {m.error ?? m.message}
                  </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>
    </div>
  )
}

function AutoSmsCard({ event }: { event: Data['events'][number] }) {
  const meta = AUTO_SMS_EVENTS.find((e) => e.key === event.key)!
  const router = useRouter()
  const save = useServerFn(updateAutoSms)
  const sendTest = useServerFn(sendAutoSmsTest)
  const textarea = useRef<HTMLTextAreaElement>(null)
  const [enabled, setEnabled] = useState(event.enabled)
  const [template, setTemplate] = useState(event.template)
  const [testPhone, setTestPhone] = useState('')
  const [saving, setSaving] = useState(false)
  const [testing, setTesting] = useState(false)

  const preview = renderAutoSms(template, sampleValues(event.key as AutoSmsEvent))
  const { length, segments } = countSegments(preview)
  const dirty = enabled !== event.enabled || template.trim() !== event.template
  const Icon = ICONS[event.key]

  function insert(key: string) {
    const el = textarea.current
    const token = `{${key}}`
    if (!el) return setTemplate((t) => t + token)
    const start = el.selectionStart
    const end = el.selectionEnd
    setTemplate((t) => t.slice(0, start) + token + t.slice(end))
    requestAnimationFrame(() => {
      el.focus()
      el.setSelectionRange(start + token.length, start + token.length)
    })
  }

  async function submit() {
    setSaving(true)
    try {
      await save({ data: { event: event.key, enabled, template } })
      toast.success(`${meta.label} saved.`)
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Your changes could not be saved.')
    } finally {
      setSaving(false)
    }
  }

  async function test() {
    setTesting(true)
    try {
      await sendTest({ data: { event: event.key, template, phone: testPhone } })
      toast.success('Test text sent.')
      await router.invalidate()
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'The test text could not be sent.')
    } finally {
      setTesting(false)
    }
  }

  return (
    <Section icon={Icon} title={meta.label} description={meta.description}>
      <label className="flex items-center justify-between gap-4 rounded-xl border bg-background/60 p-3 text-sm">
        <span className="font-medium">{enabled ? 'On: customers receive this text' : 'Off: this text is not sent'}</span>
        <Switch checked={enabled} onCheckedChange={setEnabled} aria-label={`Send the ${meta.label.toLowerCase()} text`} />
      </label>

      <div className="grid gap-2">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <Label htmlFor={`autosms-${event.key}`}>Message</Label>
          <button
            type="button"
            className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
            onClick={() => setTemplate(meta.defaultTemplate)}
          >
            <RotateCcw className="size-3" aria-hidden /> Use the default wording
          </button>
        </div>
        <Textarea
          ref={textarea}
          id={`autosms-${event.key}`}
          value={template}
          onChange={(e) => setTemplate(e.target.value)}
          maxLength={AUTO_SMS_MAX_LENGTH}
          rows={3}
        />
        <div className="flex flex-wrap gap-1.5">
          {meta.placeholders.map((p) => (
            <button
              key={p.key}
              type="button"
              title={p.hint}
              onClick={() => insert(p.key)}
              className="rounded-full border bg-secondary/60 px-2.5 py-0.5 font-mono text-xs hover:bg-secondary"
            >
              {`{${p.key}}`}
            </button>
          ))}
        </div>
      </div>

      <div className="rounded-xl bg-secondary/50 p-3 text-sm">
        <p className="text-xs font-medium text-muted-foreground">
          Preview with sample values · {length} characters · {segments} SMS part{segments === 1 ? '' : 's'}
        </p>
        <p className="mt-1 whitespace-pre-wrap">{preview}</p>
      </div>

      <div className="flex flex-wrap items-end justify-between gap-3">
        <div className="flex items-end gap-2">
          <div className="grid gap-1.5">
            <Label htmlFor={`autosms-test-${event.key}`} className="text-xs">
              Send a test to
            </Label>
            <Input
              id={`autosms-test-${event.key}`}
              type="tel"
              placeholder="024 123 4567"
              value={testPhone}
              onChange={(e) => setTestPhone(e.target.value)}
              className="w-40"
            />
          </div>
          <Button type="button" variant="outline" onClick={test} disabled={testing || !testPhone.trim() || !template.trim()}>
            {testing ? <LoaderCircle className="animate-spin" /> : <Send />} Send test
          </Button>
        </div>
        <div className="flex items-center gap-3">
          {event.updatedAt && !dirty && (
            <p className="text-xs text-muted-foreground">
              Updated by {event.updatedBy} on {dateFormat.format(new Date(event.updatedAt))}
            </p>
          )}
          <Button type="button" onClick={submit} disabled={saving || !dirty || !template.trim()}>
            <Save /> {saving ? 'Saving…' : 'Save'}
          </Button>
        </div>
      </div>
    </Section>
  )
}
