'use client'

import { useEffect, useState } from 'react'
import {
  BLOCK_LABELS,
  FIELD_TYPES,
  FIELD_TYPE_LABEL,
  VALIDATION_LABEL_DE,
  validateDefinitionInput,
  type FieldType,
} from '@/lib/intake/field-builder'
import { createFieldDefinition } from '@/app/admin/intake-fields/actions'

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

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

export default function IntakeFieldCreateModal({ onCancel, onSaved }: Props) {
  const [fieldKey, setFieldKey] = useState('')
  const [labelDe, setLabelDe] = useState('')
  const [labelEn, setLabelEn] = useState('')
  const [helpDe, setHelpDe] = useState('')
  const [helpEn, setHelpEn] = useState('')
  const [block, setBlock] = useState(1)
  const [sortOrder, setSortOrder] = useState(0)
  const [fieldType, setFieldType] = useState<FieldType>('text')
  const [isRequired, setIsRequired] = useState(false)
  const [visibleIfText, setVisibleIfText] = useState('')
  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 = validateDefinitionInput({
    field_key: fieldKey,
    block,
    label_de: labelDe,
    label_en: labelEn || null,
    helptext_de: helpDe || null,
    helptext_en: helpEn || null,
    field_type: fieldType,
    is_required: isRequired,
    visible_if_text: visibleIfText || null,
    sort_order: sortOrder,
  })

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

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="field-create-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-foreground/40 p-4"
      onClick={onCancel}
    >
      <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-create-title" className="text-base font-bold text-foreground">
            Neues Intake-Feld
          </h2>
          <p className="text-xs text-muted-foreground mt-1">
            <code className="text-[11px]">field_key</code> und <code className="text-[11px]">field_type</code> sind nach Anlage nicht mehr änderbar.
          </p>
        </header>

        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <Field label="field_key * (a-z, 0-9, _)" htmlFor="fk">
              <input
                id="fk"
                type="text"
                required
                value={fieldKey}
                onChange={(e) => setFieldKey(e.target.value.toLowerCase())}
                disabled={submitting}
                placeholder="z.B. supplier_motivation"
                className="w-full px-3 py-2 text-sm font-mono bg-background border border-border rounded-sm focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </Field>
            <Field label="Feldtyp *" htmlFor="type">
              <select
                id="type"
                value={fieldType}
                onChange={(e) => setFieldType(e.target.value as FieldType)}
                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_TYPES.map((t) => (
                  <option key={t} value={t}>
                    {FIELD_TYPE_LABEL[t]}
                  </option>
                ))}
              </select>
            </Field>
          </div>

          <Field label="Label (DE) *" htmlFor="lde">
            <input
              id="lde"
              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="len">
            <input
              id="len"
              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="hde">
            <textarea
              id="hde"
              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="hen">
            <textarea
              id="hen"
              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="blk">
              <select
                id="blk"
                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="so">
              <input
                id="so"
                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>

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

          <Field label="visible_if (JSON, optional)" htmlFor="vi">
            <textarea
              id="vi"
              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">
              Anlegen 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 ? 'Anlegen…' : 'Feld anlegen'}
            </button>
          </footer>
        </form>
      </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>
  )
}
