'use client'

import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import {
  createRedirectRule,
  updateRedirectRule,
  type RedirectRule,
  type RedirectRulePayload,
  type RedirectStatusCode,
} from '../../lib/seo-service.js'
import { Drawer } from './Drawer.js'
import { btnPrimary, btnSecondary } from './primitives.js'

const STATUS_CODES: { value: RedirectStatusCode; label: string }[] = [
  { value: 301, label: '301 — Permanent' },
  { value: 302, label: '302 — Temporary' },
  { value: 307, label: '307 — Temporary (preserve method)' },
  { value: 308, label: '308 — Permanent (preserve method)' },
  { value: 410, label: '410 — Gone (no destination)' },
]

const inputCls =
  'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'

function normalizePath(p: string): string {
  const t = p.trim()
  if (!t) return ''
  if (/^https?:\/\//i.test(t)) return t
  return t.startsWith('/') ? t : `/${t}`
}

export function RedirectEditorDrawer({
  open,
  onOpenChange,
  rule,
  onSaved,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  /** null = create mode */
  rule: RedirectRule | null
  onSaved?: () => void
}) {
  const [form, setForm] = useState<RedirectRulePayload>({
    type: 301,
    fromPath: '',
    toPath: '',
    enabled: true,
    preserveQuery: false,
    notes: '',
  })
  const [saving, setSaving] = useState(false)
  const [clientError, setClientError] = useState<string | null>(null)

  useEffect(() => {
    if (!open) return
    if (rule) {
      setForm({
        type: rule.type,
        fromPath: rule.fromPath,
        toPath: rule.toPath,
        enabled: rule.enabled,
        preserveQuery: rule.preserveQuery,
        notes: rule.notes ?? '',
      })
    } else {
      setForm({
        type: 301,
        fromPath: '',
        toPath: '',
        enabled: true,
        preserveQuery: false,
        notes: '',
      })
    }
    setClientError(null)
  }, [open, rule])

  const isGone = form.type === 410
  const update = (patch: Partial<RedirectRulePayload>) => setForm((f) => ({ ...f, ...patch }))

  async function handleSave() {
    const fromPath = normalizePath(form.fromPath)
    const toPath = isGone ? '' : normalizePath(form.toPath)
    if (!fromPath) {
      setClientError('Source path is required.')
      return
    }
    if (!isGone && !toPath) {
      setClientError('Destination is required for redirect status codes.')
      return
    }
    if (!isGone && fromPath === toPath) {
      setClientError('Source and destination cannot be identical (would create a loop).')
      return
    }
    setClientError(null)
    setSaving(true)
    const payload: RedirectRulePayload = { ...form, fromPath, toPath }
    const res = rule
      ? await updateRedirectRule(rule.id, payload)
      : await createRedirectRule(payload)
    setSaving(false)
    if (res.error) {
      toast.error(res.error)
      return
    }
    toast.success(rule ? 'Redirect updated.' : 'Redirect created.')
    onOpenChange(false)
    onSaved?.()
  }

  return (
    <Drawer
      open={open}
      onOpenChange={onOpenChange}
      title={rule ? 'Edit redirect' : 'New redirect'}
      width="max-w-lg"
      footer={
        <>
          <button className={btnSecondary} onClick={() => onOpenChange(false)} disabled={saving}>
            Cancel
          </button>
          <button className={btnPrimary} onClick={handleSave} disabled={saving}>
            {saving ? 'Saving…' : rule ? 'Save changes' : 'Create redirect'}
          </button>
        </>
      }
    >
      <div className="space-y-4">
        {clientError && (
          <p
            className="text-destructive bg-destructive/10 rounded-md px-3 py-2 text-sm"
            role="alert"
          >
            {clientError}
          </p>
        )}
        <div className="space-y-1.5">
          <label className="text-foreground text-sm font-medium" htmlFor="redir-type">
            Status code
          </label>
          <select
            id="redir-type"
            className={inputCls}
            value={form.type}
            onChange={(e) => update({ type: Number(e.target.value) as RedirectStatusCode })}
          >
            {STATUS_CODES.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>

        <div className="space-y-1.5">
          <label className="text-foreground text-sm font-medium" htmlFor="redir-from">
            Source path
          </label>
          <input
            id="redir-from"
            className={inputCls}
            value={form.fromPath}
            onChange={(e) => update({ fromPath: e.target.value })}
            placeholder="/old-path"
          />
        </div>

        {!isGone && (
          <div className="space-y-1.5">
            <label className="text-foreground text-sm font-medium" htmlFor="redir-to">
              Destination
            </label>
            <input
              id="redir-to"
              className={inputCls}
              value={form.toPath}
              onChange={(e) => update({ toPath: e.target.value })}
              placeholder="/new-path or https://example.com/page"
            />
          </div>
        )}

        <div className="space-y-1.5">
          <label className="text-foreground text-sm font-medium" htmlFor="redir-notes">
            Notes <span className="text-muted-foreground font-normal">(optional)</span>
          </label>
          <input
            id="redir-notes"
            className={inputCls}
            value={form.notes ?? ''}
            onChange={(e) => update({ notes: e.target.value })}
            placeholder="Why this redirect exists"
          />
        </div>

        <div className="border-border space-y-3 rounded-lg border p-4">
          <label className="flex items-center justify-between gap-3">
            <span className="text-foreground text-sm font-medium">Enabled</span>
            <input
              type="checkbox"
              role="switch"
              aria-checked={!!form.enabled}
              checked={!!form.enabled}
              onChange={(e) => update({ enabled: e.target.checked })}
              className="accent-primary h-4 w-4"
            />
          </label>
          {!isGone && (
            <label className="flex items-center justify-between gap-3">
              <span className="min-w-0">
                <span className="text-foreground block text-sm font-medium">
                  Preserve query string
                </span>
                <span className="text-muted-foreground block text-sm">
                  Append the original query params to the destination.
                </span>
              </span>
              <input
                type="checkbox"
                role="switch"
                aria-checked={!!form.preserveQuery}
                checked={!!form.preserveQuery}
                onChange={(e) => update({ preserveQuery: e.target.checked })}
                className="accent-primary h-4 w-4 shrink-0"
              />
            </label>
          )}
        </div>
      </div>
    </Drawer>
  )
}
