'use client'

import { useEffect, useState } from 'react'
import { normalizeSlug, validateSlug } from '@actuate-media/cms-core/client'
import { Modal } from '../../components/ui/Modal.js'
import { Button } from '../../components/ui/Button.js'
import { SeoCharCount } from '../../components/seo/SeoCharCount.js'
import type { EditorPage } from '../../lib/page-editor-service.js'

const SEO_TITLE_MIN = 30
const SEO_TITLE_MAX = 60
const SEO_DESC_MIN = 120
const SEO_DESC_MAX = 160

interface PageSettingsModalProps {
  open: boolean
  page: EditorPage
  canEdit: boolean
  onClose: () => void
  onSave: (patch: Partial<EditorPage>) => void
}

const LABEL = 'text-foreground mb-1 block text-xs font-medium'
const INPUT =
  'border-input bg-input-background text-foreground focus-visible:ring-ring w-full rounded-md border px-2.5 py-1.5 text-sm focus-visible:ring-2 focus-visible:outline-none'

const slugify = normalizeSlug

/** Edits page-level fields: title, slug, path, and SEO. */
export function PageSettingsModal({
  open,
  page,
  canEdit,
  onClose,
  onSave,
}: PageSettingsModalProps) {
  const [title, setTitle] = useState(page.title)
  const [slug, setSlug] = useState(page.slug)
  const [path, setPath] = useState(page.path)
  const [seoTitle, setSeoTitle] = useState(page.seoTitle)
  const [seoDescription, setSeoDescription] = useState(page.seoDescription)
  // Auto-derive slug/path from title until the user edits slug manually.
  const [slugTouched, setSlugTouched] = useState(Boolean(page.slug))

  useEffect(() => {
    if (!open) return
    setTitle(page.title)
    setSlug(page.slug)
    setPath(page.path)
    setSeoTitle(page.seoTitle)
    setSeoDescription(page.seoDescription)
    setSlugTouched(Boolean(page.slug))
  }, [open, page])

  function handleTitle(next: string) {
    setTitle(next)
    if (!slugTouched) {
      const s = slugify(next)
      setSlug(s)
      if (!page.path || page.path === `/${slug}`) setPath(s ? `/${s}` : '')
    }
  }

  const slugError = validateSlug(slug)

  function handleSave() {
    if (slugError) return
    onSave({ title, slug, path: path || (slug ? `/${slug}` : '/'), seoTitle, seoDescription })
    onClose()
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Page settings"
      actions={
        <>
          <Button variant="ghost" onClick={onClose}>
            Cancel
          </Button>
          <Button variant="primary" onClick={handleSave} disabled={!canEdit || Boolean(slugError)}>
            Done
          </Button>
        </>
      }
    >
      <div className="space-y-3">
        <div>
          <label className={LABEL} htmlFor="ps-title">
            Title <span className="text-destructive">*</span>
          </label>
          <input
            id="ps-title"
            className={INPUT}
            value={title}
            disabled={!canEdit}
            onChange={(e) => handleTitle(e.target.value)}
          />
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={LABEL} htmlFor="ps-slug">
              Slug
            </label>
            <input
              id="ps-slug"
              className={INPUT}
              value={slug}
              disabled={!canEdit}
              aria-invalid={Boolean(slugError)}
              aria-describedby={slugError ? 'ps-slug-error' : undefined}
              onChange={(e) => {
                setSlugTouched(true)
                setSlug(slugify(e.target.value))
              }}
            />
            {slugError && (
              <p id="ps-slug-error" className="text-destructive mt-1 text-xs">
                {slugError}
              </p>
            )}
          </div>
          <div>
            <label className={LABEL} htmlFor="ps-path">
              Path <span className="text-destructive">*</span>
            </label>
            <input
              id="ps-path"
              className={INPUT}
              value={path}
              disabled={!canEdit}
              placeholder="/about/story"
              onChange={(e) => setPath(e.target.value)}
            />
          </div>
        </div>
        <div>
          <div className="mb-1 flex items-center justify-between">
            <label className={`${LABEL} mb-0`} htmlFor="ps-seo-title">
              SEO title
            </label>
            <SeoCharCount value={seoTitle} min={SEO_TITLE_MIN} max={SEO_TITLE_MAX} />
          </div>
          <input
            id="ps-seo-title"
            className={INPUT}
            value={seoTitle}
            disabled={!canEdit}
            placeholder={title || 'Defaults to the page title'}
            onChange={(e) => setSeoTitle(e.target.value)}
          />
        </div>
        <div>
          <div className="mb-1 flex items-center justify-between">
            <label className={`${LABEL} mb-0`} htmlFor="ps-seo-desc">
              SEO description
            </label>
            <SeoCharCount value={seoDescription} min={SEO_DESC_MIN} max={SEO_DESC_MAX} />
          </div>
          <textarea
            id="ps-seo-desc"
            className={`${INPUT} min-h-[64px] resize-y`}
            value={seoDescription}
            disabled={!canEdit}
            placeholder="Summarize the page for search results (120–160 characters)"
            onChange={(e) => setSeoDescription(e.target.value)}
          />
        </div>
      </div>
    </Modal>
  )
}
