'use client'

import { useEffect, useState } from 'react'
import {
  loadProjectsForPicker,
  loadSuppliersForPicker,
  updateAnalysisHeader,
  type ProjectPickerItem,
  type SupplierPickerItem,
} from '@/app/oee/analyse/actions'
import {
  VALIDATION_LABEL_DE,
  validateHeaderInput,
  type HeaderInput,
  type OeeAnalysisHeader,
} from '@/lib/oee/analysis'

type Props = {
  analysisId: string
  header: OeeAnalysisHeader
  onSaved: () => void
}

export default function AnalysisHeaderForm({ analysisId, header, onSaved }: Props) {
  const [projects, setProjects] = useState<ProjectPickerItem[]>([])
  const [suppliers, setSuppliers] = useState<SupplierPickerItem[]>([])
  const [name, setName] = useState(header.name ?? '')
  const [projectId, setProjectId] = useState<string>(header.project_id ?? '')
  const [supplierId, setSupplierId] = useState<string>(header.supplier_id ?? '')
  const [analysisDate, setAnalysisDate] = useState(header.analysis_date ?? '')
  const [periodStart, setPeriodStart] = useState(header.period_start ?? '')
  const [periodEnd, setPeriodEnd] = useState(header.period_end ?? '')
  const [mode, setMode] = useState<'with_project' | 'orphan'>(
    header.is_orphan ? 'orphan' : 'with_project',
  )
  const [submitting, setSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      const [projRes, supRes] = await Promise.all([
        loadProjectsForPicker(),
        loadSuppliersForPicker(),
      ])
      if (cancelled) return
      if (projRes.ok && projRes.data) setProjects(projRes.data)
      if (supRes.ok && supRes.data) setSuppliers(supRes.data)
    })()
    return () => {
      cancelled = true
    }
  }, [])

  const input: HeaderInput = {
    name,
    project_id: mode === 'with_project' ? projectId || null : null,
    supplier_id: mode === 'with_project' ? null : supplierId || null,
    analysis_date: analysisDate,
    period_start: periodStart || null,
    period_end: periodEnd || null,
  }
  const validation = validateHeaderInput(input, mode)
  const canSubmit = validation.ok && !submitting

  async function handleSubmit(ev: React.FormEvent) {
    ev.preventDefault()
    if (!canSubmit) return
    setSubmitting(true)
    setErrorMsg(null)
    const result = await updateAnalysisHeader(analysisId, input)
    setSubmitting(false)
    if (!result.ok) {
      setErrorMsg(result.error)
      return
    }
    onSaved()
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 bg-card border border-border rounded-md p-5">
      <fieldset className="space-y-2">
        <legend className="text-xs font-condensed font-bold text-foreground">Verknüpfung</legend>
        <label className="flex items-center gap-2 text-sm">
          <input
            type="radio"
            name="mode"
            checked={mode === 'with_project'}
            onChange={() => setMode('with_project')}
            disabled={submitting}
          />
          Mit Projekt verknüpfen
        </label>
        <label className="flex items-center gap-2 text-sm">
          <input
            type="radio"
            name="mode"
            checked={mode === 'orphan'}
            onChange={() => setMode('orphan')}
            disabled={submitting}
          />
          Ohne Projekt (Sandbox-Analyse)
        </label>
      </fieldset>

      {mode === 'with_project' ? (
        <Picker
          label="Projekt *"
          id="proj"
          value={projectId}
          onChange={setProjectId}
          options={projects.map((p) => ({
            value: p.id,
            label: `${p.project_code ?? p.id.slice(0, 8)} · ${p.supplier_name ?? '—'}`,
          }))}
          disabled={submitting}
        />
      ) : (
        <Picker
          label="Lieferant *"
          id="sup"
          value={supplierId}
          onChange={setSupplierId}
          options={suppliers.map((s) => ({ value: s.id, label: s.supplier_name }))}
          disabled={submitting}
        />
      )}

      <Field label="Name *" htmlFor="name">
        <input
          id="name"
          type="text"
          required
          value={name}
          onChange={(e) => setName(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-3 gap-3">
        <Field label="Analyse-Datum *" htmlFor="adate">
          <input
            id="adate"
            type="date"
            required
            value={analysisDate}
            onChange={(e) => setAnalysisDate(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="Zeitraum von" htmlFor="pstart">
          <input
            id="pstart"
            type="date"
            value={periodStart}
            onChange={(e) => setPeriodStart(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="Zeitraum bis" htmlFor="pend">
          <input
            id="pend"
            type="date"
            value={periodEnd}
            onChange={(e) => setPeriodEnd(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>

      {!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-3 border-t border-border">
        <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…' : 'Speichern und weiter →'}
        </button>
      </footer>
    </form>
  )
}

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>
  )
}

function Picker({
  label,
  id,
  value,
  onChange,
  options,
  disabled,
}: {
  label: string
  id: string
  value: string
  onChange: (v: string) => void
  options: { value: string; label: string }[]
  disabled?: boolean
}) {
  return (
    <Field label={label} htmlFor={id}>
      <select
        id={id}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required
        disabled={disabled}
        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"
      >
        <option value="">— bitte wählen —</option>
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </Field>
  )
}
