'use client'

import { useEffect, useState } from 'react'
import {
  BLOCK_LABELS,
  FIELD_TYPE_LABEL,
  VALIDATION_LABEL_DE,
  validateUpdateDefinitionInput,
  type FieldDefinition,
} from '@/lib/intake/field-builder'
import { updateFieldDefinition } from '@/app/admin/intake-fields/actions'

type Props = {
  definition: FieldDefinition
  onCancel: () => void
  onSaved: () => void
}

const BLOCK_VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9]

export default function IntakeFieldEditModal({ definition, onCancel, onSaved }: Props) {
  const [labelDe, setLabelDe] = useState(definition.label_de)
  const [labelEn, setLabelEn] = useState(definition.label_en ?? '')
  const [helpDe, setHelpDe] = useState(definition.helptext_de ?? '')
  const [helpEn, setHelpEn] = useState(definition.helptext_en ?? '')
  const [block, setBlock] = useState(definition.block)
  const [sortOrder, setSortOrder] = useState(definition.sort_order)
  const [isRequired, setIsRequired] = useState(definition.is_required)
  const [isActive, setIsActive] = useState(definition.is_active)
  const [visibleIfText, setVisibleIfText] = useState(
    definition.visible_if ? JSON.stringify(definition.visible_if, null, 2) : '',
  )
  const [submitting, setSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)

  useEffect(() => {
    function onEsc(ev: KeyboardEvent) {
      if (ev.key === 'Escape' && !submitting) onCancel()
    }
    window.addEventListener('keydown', onEsc)
    return () => window.removeEventListener('keydown', onEsc)
  }, [onCancel, submitting])

  const validation = validateUpdateDefinitionInput({
    block,
    label_de: labelDe,
    label_en: labelEn || null,
    helptext_de: helpDe || null,
    helptext_en: helpEn || null,
    is_required: isRequired,
    visible_if_text: visibleIfText || null,
    sort_order: sortOrder,
    is_active: isActive,
  })

  async function handleSubmit(ev: React.FormEvent) {
    ev.preventDefault()
    if (!validation.ok) return
    setSubmitting(true)
    setErrorMsg(null)
    const result = await updateFieldDefinition(definition.id, {
      block,
      label_de: labelDe,
      label_en: labelEn || null,
      helptext_de: helpDe || null,
      helptext_en: helpEn || null,
      is_required: isRequired,
      visible_if_text: visibleIfText || null,
      sort_order: sortOrder,
      is_active: isActive,
    })
    setSubmitting(false)
    if (!result.ok) {
      setErrorMsg(result.error)
      return
    }
    onSaved()
  }

  return (
    <Shell title={`Bearbeiten — ${definition.field_key}`} onClose={onCancel}>
      <form onSubmit={handleSubmit} className="space-y-3">
        <p className="text-[11px] text-muted-foreground">
          Locked: <code>{definition.field_key}</code> · {FIELD_TYPE_LABEL[definition.field_type]}
        </p>

        <Field label="Label (DE) *" htmlFor="label-de">
          <input
            id="label-de"
            type="text"
            required
            value={labelDe}
            onChange={(e) => setLabelDe(e.target.value)}
            disabled={submitting}
            className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </Field>
        <Field label="Label (EN)" htmlFor="label-en">
          <input
            id="label-en"
            type="text"
            value={labelEn}
            onChange={(e) => setLabelEn(e.target.value)}
            disabled={submitting}
            className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </Field>

        <Field label="Hilfetext (DE)" htmlFor="help-de">
          <textarea
            id="help-de"
            rows={2}
            value={helpDe}
            onChange={(e) => setHelpDe(e.target.value)}
            disabled={submitting}
            className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </Field>
        <Field label="Hilfetext (EN)" htmlFor="help-en">
          <textarea
            id="help-en"
            rows={2}
            value={helpEn}
            onChange={(e) => setHelpEn(e.target.value)}
            disabled={submitting}
            className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </Field>

        <div className="grid grid-cols-2 gap-3">
          <Field label="Block" htmlFor="block">
            <select
              id="block"
              value={block}
              onChange={(e) => setBlock(Number(e.target.value))}
              disabled={submitting}
              className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
            >
              {BLOCK_VALUES.map((b) => (
                <option key={b} value={b}>
                  {BLOCK_LABELS[b]}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Sort-Order" htmlFor="sort">
            <input
              id="sort"
              type="number"
              min={0}
              step={1}
              value={sortOrder}
              onChange={(e) => setSortOrder(Number(e.target.value))}
              disabled={submitting}
              className="w-full px-3 py-2 text-sm bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </Field>
        </div>

        <div className="flex items-center gap-4">
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={isRequired}
              onChange={(e) => setIsRequired(e.target.checked)}
              disabled={submitting}
            />
            Pflichtfeld
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={isActive}
              onChange={(e) => setIsActive(e.target.checked)}
              disabled={submitting}
            />
            Aktiv
          </label>
        </div>

        <Field label="visible_if (JSON, optional)" htmlFor="visible-if">
          <textarea
            id="visible-if"
            rows={3}
            value={visibleIfText}
            onChange={(e) => setVisibleIfText(e.target.value)}
            disabled={submitting}
            placeholder='z.B. {"field":"intake_type","equals":"lsc_workshop"}'
            className="w-full px-3 py-2 text-xs font-mono bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </Field>

        {!validation.ok && (
          <p className="text-xs text-destructive">
            {VALIDATION_LABEL_DE[validation.error] ?? validation.error}
          </p>
        )}
        {errorMsg && (
          <p className="text-xs text-destructive" role="alert">
            Speichern fehlgeschlagen: {errorMsg}
          </p>
        )}

        <footer className="flex items-center justify-end gap-2 pt-2 border-t border-border">
          <button
            type="button"
            onClick={onCancel}
            disabled={submitting}
            className="px-3 py-1.5 text-sm font-condensed text-foreground border border-border rounded-sm hover:bg-muted disabled:opacity-50"
          >
            Abbrechen
          </button>
          <button
            type="submit"
            disabled={!validation.ok || submitting}
            className="px-3 py-1.5 text-sm font-condensed font-bold text-white bg-primary rounded-sm hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {submitting ? 'Speichern…' : 'Speichern'}
          </button>
        </footer>
      </form>
    </Shell>
  )
}

function Shell({
  title,
  onClose,
  children,
}: {
  title: string
  onClose: () => void
  children: React.ReactNode
}) {
  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="field-edit-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-foreground/40 p-4"
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="bg-card border border-border rounded-md shadow-lg w-full max-w-lg p-5 space-y-4 max-h-[90vh] overflow-y-auto"
      >
        <header>
          <h2 id="field-edit-title" className="text-base font-bold text-foreground">
            {title}
          </h2>
        </header>
        {children}
      </div>
    </div>
  )
}

function Field({
  label,
  htmlFor,
  children,
}: {
  label: string
  htmlFor: string
  children: React.ReactNode
}) {
  return (
    <div className="space-y-1">
      <label htmlFor={htmlFor} className="text-xs font-condensed font-bold text-foreground">
        {label}
      </label>
      {children}
    </div>
  )
}
