'use client'

// Inline rename for a comparison (KAR-846, migration #106). Click the pencil,
// type, Enter/blur saves; empty clears back to the default label.
// tdd-guard:skip — thin action trigger.

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Check, Pencil, X } from 'lucide-react'
import { saveComparisonTitle } from '@/app/qaf-differences/comparison-meta-actions'

interface Props {
  comparisonId: string
  title: string | null
  /** Shown when no custom title is set (part number / mode label). */
  fallback: string
}

export default function QafTitleEditor({ comparisonId, title, fallback }: Props) {
  const router = useRouter()
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState(title ?? '')
  const [pending, startTransition] = useTransition()
  const [error, setError] = useState<string | null>(null)

  function save() {
    setError(null)
    startTransition(async () => {
      const res = await saveComparisonTitle(comparisonId, draft)
      if (res.ok) {
        setEditing(false)
        router.refresh()
      } else {
        setError(res.error)
      }
    })
  }

  if (!editing) {
    return (
      <span className="inline-flex items-center gap-2">
        <h1 className="font-display uppercase tracking-tight text-xl font-bold text-foreground">
          {title || fallback}
        </h1>
        <button
          type="button"
          onClick={() => {
            setDraft(title ?? '')
            setEditing(true)
          }}
          aria-label="Vergleich umbenennen"
          className="text-muted-foreground hover:text-foreground print:hidden"
        >
          <Pencil size={14} />
        </button>
      </span>
    )
  }

  return (
    <span className="inline-flex items-center gap-2">
      <input
        autoFocus
        value={draft}
        maxLength={120}
        placeholder={fallback}
        disabled={pending}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') save()
          if (e.key === 'Escape') setEditing(false)
        }}
        className="rounded border border-border bg-background px-2 py-1 text-lg font-bold text-foreground"
      />
      <button type="button" onClick={save} disabled={pending} aria-label="Speichern" className="text-success-text">
        <Check size={16} />
      </button>
      <button
        type="button"
        onClick={() => setEditing(false)}
        disabled={pending}
        aria-label="Abbrechen"
        className="text-muted-foreground hover:text-foreground"
      >
        <X size={16} />
      </button>
      {error && <span className="text-xs text-destructive">{error}</span>}
    </span>
  )
}
