'use client'

import { useEffect, useRef, useState } from 'react'
import { saveOwnAvailability, deleteOwnAvailability } from '@/app/intake/board/actions'
import {
  STATUS_LABEL_DE,
  validateAvailabilityInput,
  type AvailabilityStatus,
  type ConsultantAvailability,
} from '@/lib/intake/availability'

type Props = {
  initialDate: string
  existing: ConsultantAvailability[]
  onCancel: () => void
  onSaved: () => void
}

const STATUS_OPTIONS: AvailabilityStatus[] = ['free', 'partial', 'full', 'vacation', 'blocked']

const ERR_LABEL: Record<string, string> = {
  start_required: 'Start-Datum fehlt',
  end_required: 'Ende-Datum fehlt',
  end_before_start: 'Ende vor Start',
  invalid_status: 'Ungültiger Status',
}

export default function AvailabilityEditModal({
  initialDate,
  existing,
  onCancel,
  onSaved,
}: Props) {
  const [startDate, setStartDate] = useState(initialDate)
  const [endDate, setEndDate] = useState(initialDate)
  const [status, setStatus] = useState<AvailabilityStatus>('vacation')
  const [note, setNote] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)
  const firstFieldRef = useRef<HTMLInputElement | null>(null)

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

  const validation = validateAvailabilityInput({ startDate, endDate, status, note: note || null })
  const canSubmit = validation.ok && !submitting

  async function handleSubmit(ev: React.FormEvent) {
    ev.preventDefault()
    if (!canSubmit) return
    setSubmitting(true)
    setErrorMsg(null)
    const result = await saveOwnAvailability(startDate, endDate, status, note || null)
    setSubmitting(false)
    if (!result.ok) {
      setErrorMsg(result.error)
      return
    }
    onSaved()
  }

  async function handleDelete(id: string) {
    setSubmitting(true)
    setErrorMsg(null)
    const result = await deleteOwnAvailability(id)
    setSubmitting(false)
    if (!result.ok) {
      setErrorMsg(result.error)
      return
    }
    onSaved()
  }

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="availability-modal-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-md p-5 space-y-4"
      >
        <header>
          <h2 id="availability-modal-title" className="text-base font-bold text-foreground">
            Meine Verfügbarkeit pflegen
          </h2>
          <p className="text-xs text-muted-foreground mt-1">
            Eintrag für deine Zeile in der Timeline.
          </p>
        </header>

        {existing.length > 0 && (
          <section className="space-y-2">
            <h3 className="text-xs font-condensed font-bold text-foreground">
              Aktive Einträge im Sichtbereich
            </h3>
            <ul className="space-y-1.5 text-xs">
              {existing.map((e) => (
                <li
                  key={e.id}
                  className="flex items-center justify-between gap-2 p-2 bg-muted/40 border border-border rounded-sm"
                >
                  <div className="flex flex-col">
                    <span className="font-condensed">
                      {e.start_date} → {e.end_date} · {STATUS_LABEL_DE[e.status]}
                    </span>
                    {e.note && (
                      <span className="text-muted-foreground text-[11px] truncate">{e.note}</span>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDelete(e.id)}
                    disabled={submitting}
                    className="text-[11px] font-condensed text-destructive hover:underline disabled:opacity-50"
                  >
                    Löschen
                  </button>
                </li>
              ))}
            </ul>
          </section>
        )}

        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <label htmlFor="avail-start" className="text-xs font-condensed font-bold text-foreground">
                Von <span className="text-destructive">*</span>
              </label>
              <input
                ref={firstFieldRef}
                id="avail-start"
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                required
                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"
              />
            </div>
            <div className="space-y-1.5">
              <label htmlFor="avail-end" className="text-xs font-condensed font-bold text-foreground">
                Bis <span className="text-destructive">*</span>
              </label>
              <input
                id="avail-end"
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                required
                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"
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <label htmlFor="avail-status" className="text-xs font-condensed font-bold text-foreground">
              Status <span className="text-destructive">*</span>
            </label>
            <select
              id="avail-status"
              value={status}
              onChange={(e) => setStatus(e.target.value as AvailabilityStatus)}
              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"
            >
              {STATUS_OPTIONS.map((s) => (
                <option key={s} value={s}>
                  {STATUS_LABEL_DE[s]}
                </option>
              ))}
            </select>
          </div>

          <div className="space-y-1.5">
            <label htmlFor="avail-note" className="text-xs font-condensed font-bold text-foreground">
              Notiz <span className="text-muted-foreground font-normal">(optional)</span>
            </label>
            <input
              id="avail-note"
              type="text"
              value={note}
              onChange={(e) => setNote(e.target.value)}
              maxLength={200}
              disabled={submitting}
              placeholder="z.B. Kundenworkshop / Krank / Reserviert für X"
              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"
            />
          </div>

          {!validation.ok && (
            <p className="text-xs text-destructive">{ERR_LABEL[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"
            >
              Schließen
            </button>
            <button
              type="submit"
              disabled={!canSubmit}
              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…' : 'Eintrag anlegen'}
            </button>
          </footer>
        </form>
      </div>
    </div>
  )
}
