'use client'

import { useState, useEffect } from 'react'

export interface SlugFieldProps {
  label: string
  value?: string
  onChange: (value: string) => void
  from?: string
  required?: boolean
  helpText?: string
}

// Mirrors `normalizeSlug` in @actuate-media/cms-core so the live-edited value
// matches what the server will accept (lowercase alphanumerics + single
// hyphens; underscores and other punctuation are collapsed to hyphens).
function toSlug(text: string): string {
  return text
    .toLowerCase()
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

export function SlugField({ label, value = '', onChange, required, helpText }: SlugFieldProps) {
  const [locked, setLocked] = useState(true)

  return (
    <div>
      <label className="mb-1 block text-sm font-medium">
        {label}
        {required && <span className="ml-0.5 text-[var(--destructive)]">*</span>}
      </label>
      <div className="flex items-center gap-2">
        <div className="flex flex-1 items-center rounded-md border border-[var(--border)] bg-[var(--input-background)]">
          <span className="pl-3 text-sm text-[var(--muted-foreground)]">/</span>
          <input
            type="text"
            value={value}
            onChange={(e) => onChange(toSlug(e.target.value))}
            readOnly={locked}
            className="flex-1 bg-transparent px-1 py-2 text-sm outline-none"
          />
        </div>
        <button
          type="button"
          onClick={() => setLocked((l) => !l)}
          className="rounded-md border border-[var(--border)] p-2 text-sm hover:bg-[var(--accent)]"
          aria-label={locked ? 'Unlock slug' : 'Lock slug'}
        >
          <svg
            className="h-4 w-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            {locked ? (
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
              />
            ) : (
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"
              />
            )}
          </svg>
        </button>
      </div>
      {value && (
        <p className="mt-1 text-xs text-[var(--muted-foreground)]">URL preview: /{value}</p>
      )}
      {helpText && <p className="mt-1 text-xs text-[var(--muted-foreground)]">{helpText}</p>}
    </div>
  )
}
