'use client'

import { useEffect, useState, useTransition } from 'react'
import {
  createStation,
  deleteStation,
  loadProcessStepsForProject,
  updateStation,
  type ProcessStepPickerItem,
} from '@/app/oee/analyse/actions'
import {
  MAX_STATIONS_UI,
  VALIDATION_LABEL_DE,
  validateStationInput,
  type OeeStation,
} from '@/lib/oee/analysis'

type Props = {
  analysisId: string
  projectId: string | null
  stations: OeeStation[]
  onMutated: () => void
  onNext: () => void
  onPrev: () => void
}

export default function AnalysisStationsManager({
  analysisId,
  projectId,
  stations,
  onMutated,
  onNext,
  onPrev,
}: Props) {
  const [processSteps, setProcessSteps] = useState<ProcessStepPickerItem[]>([])
  const [newName, setNewName] = useState('')
  const [selectedProcessStepId, setSelectedProcessStepId] = useState<string>('')
  const [errorMsg, setErrorMsg] = useState<string | null>(null)
  const [isPending, startTransition] = useTransition()

  useEffect(() => {
    if (!projectId) {
      setProcessSteps([])
      return
    }
    let cancelled = false
    ;(async () => {
      const result = await loadProcessStepsForProject(projectId)
      if (cancelled) return
      if (result.ok && result.data) setProcessSteps(result.data)
    })()
    return () => {
      cancelled = true
    }
  }, [projectId])

  const nextOrderIdx = stations.length
  const canAdd = stations.length < MAX_STATIONS_UI
  const addValidation = validateStationInput({
    name: newName,
    linked_process_step_id: selectedProcessStepId || null,
    order_idx: nextOrderIdx,
  })

  function handleAdd(ev: React.FormEvent) {
    ev.preventDefault()
    if (!addValidation.ok || !canAdd) return
    setErrorMsg(null)
    startTransition(async () => {
      const result = await createStation(analysisId, {
        name: newName.trim(),
        linked_process_step_id: selectedProcessStepId || null,
        order_idx: nextOrderIdx,
      })
      if (!result.ok) {
        setErrorMsg(`Anlegen fehlgeschlagen: ${result.error}`)
        return
      }
      setNewName('')
      setSelectedProcessStepId('')
      onMutated()
    })
  }

  function handleImportFromProcessStep(item: ProcessStepPickerItem) {
    if (!canAdd) return
    setErrorMsg(null)
    startTransition(async () => {
      const result = await createStation(analysisId, {
        name: item.station_name,
        linked_process_step_id: item.id,
        order_idx: nextOrderIdx,
      })
      if (!result.ok) {
        setErrorMsg(`Import fehlgeschlagen: ${result.error}`)
        return
      }
      onMutated()
    })
  }

  function handleDelete(stationId: string) {
    setErrorMsg(null)
    startTransition(async () => {
      const result = await deleteStation(stationId, analysisId)
      if (!result.ok) {
        setErrorMsg(`Löschen fehlgeschlagen: ${result.error}`)
        return
      }
      onMutated()
    })
  }

  function handleMove(station: OeeStation, delta: -1 | 1) {
    const newIdx = station.order_idx + delta
    if (newIdx < 0 || newIdx >= stations.length) return
    const swapWith = stations.find((s) => s.order_idx === newIdx)
    setErrorMsg(null)
    startTransition(async () => {
      await updateStation(station.id, analysisId, {
        name: station.name,
        linked_process_step_id: station.linked_process_step_id,
        order_idx: newIdx,
      })
      if (swapWith) {
        await updateStation(swapWith.id, analysisId, {
          name: swapWith.name,
          linked_process_step_id: swapWith.linked_process_step_id,
          order_idx: station.order_idx,
        })
      }
      onMutated()
    })
  }

  const importableSteps = processSteps.filter(
    (ps) => !stations.some((s) => s.linked_process_step_id === ps.id),
  )

  return (
    <section className="space-y-5">
      <div className="bg-card border border-border rounded-md p-5 space-y-3">
        <h2 className="text-base font-bold text-foreground">Stationen</h2>
        <p className="text-xs text-muted-foreground">
          {stations.length} / {MAX_STATIONS_UI} Stationen · Reihenfolge per ↑/↓ ändern · Maximum {MAX_STATIONS_UI} im UI
        </p>

        {stations.length === 0 ? (
          <p className="text-sm text-muted-foreground italic py-2">Noch keine Stationen.</p>
        ) : (
          <ul className="divide-y divide-border border border-border rounded-sm">
            {stations.map((station) => (
              <li key={station.id} className="flex items-center gap-2 px-3 py-2" aria-busy={isPending}>
                <span className="text-xs font-condensed text-muted-foreground w-6 text-right tabular-nums">
                  {station.order_idx + 1}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-bold text-foreground truncate">{station.name}</div>
                  {station.linked_process_step_id && (
                    <div className="text-[11px] text-muted-foreground">verknüpft mit process_step</div>
                  )}
                </div>
                <button
                  type="button"
                  onClick={() => handleMove(station, -1)}
                  disabled={isPending || station.order_idx === 0}
                  className="px-2 py-1 text-xs border border-border rounded-sm hover:bg-muted disabled:opacity-50"
                  aria-label="Hoch"
                >
                  ↑
                </button>
                <button
                  type="button"
                  onClick={() => handleMove(station, 1)}
                  disabled={isPending || station.order_idx === stations.length - 1}
                  className="px-2 py-1 text-xs border border-border rounded-sm hover:bg-muted disabled:opacity-50"
                  aria-label="Runter"
                >
                  ↓
                </button>
                <button
                  type="button"
                  onClick={() => handleDelete(station.id)}
                  disabled={isPending}
                  className="px-2 py-1 text-[11px] font-condensed text-destructive border border-destructive/30 rounded-sm hover:bg-destructive/10 disabled:opacity-50"
                >
                  Löschen
                </button>
              </li>
            ))}
          </ul>
        )}

        {!canAdd && (
          <p className="text-xs text-warning bg-warning/5 border border-warning/30 rounded-sm px-3 py-2">
            Maximum von {MAX_STATIONS_UI} Stationen erreicht. Lösche eine, um eine neue hinzuzufügen.
          </p>
        )}
      </div>

      <form onSubmit={handleAdd} className="bg-card border border-border rounded-md p-5 space-y-3">
        <h3 className="text-sm font-bold text-foreground">Neue Station hinzufügen</h3>
        <div className="space-y-2">
          <input
            type="text"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Stations-Name"
            disabled={isPending || !canAdd}
            required
            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"
          />
          {!addValidation.ok && newName && (
            <p className="text-xs text-destructive">
              {VALIDATION_LABEL_DE[addValidation.error] ?? addValidation.error}
            </p>
          )}
        </div>
        <button
          type="submit"
          disabled={!addValidation.ok || isPending || !canAdd}
          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"
        >
          + Station hinzufügen
        </button>
      </form>

      {projectId && importableSteps.length > 0 && (
        <div className="bg-card border border-border rounded-md p-5 space-y-3">
          <h3 className="text-sm font-bold text-foreground">Aus LSC / Process-Steps importieren</h3>
          <p className="text-xs text-muted-foreground">
            Übernimm Stationen aus dem LSC-Workshop dieses Projekts.
          </p>
          <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {importableSteps.map((ps) => (
              <li key={ps.id}>
                <button
                  type="button"
                  onClick={() => handleImportFromProcessStep(ps)}
                  disabled={isPending || !canAdd}
                  className="w-full px-3 py-2 text-left text-xs bg-muted/40 border border-border rounded-sm hover:bg-primary/10 hover:border-primary/30 disabled:opacity-50"
                >
                  <span className="font-bold text-foreground">{ps.station_name}</span>
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}

      {errorMsg && (
        <div role="alert" className="px-3 py-2 bg-destructive/10 border border-destructive/30 text-destructive text-xs rounded-sm">
          {errorMsg}
        </div>
      )}

      <footer className="flex items-center justify-between gap-2 pt-2">
        <button
          type="button"
          onClick={onPrev}
          className="px-3 py-1.5 text-sm font-condensed text-foreground border border-border rounded-sm hover:bg-muted"
        >
          ← Zurück zu Grunddaten
        </button>
        <button
          type="button"
          onClick={onNext}
          disabled={stations.length === 0}
          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"
        >
          Weiter zu Messungen →
        </button>
      </footer>
    </section>
  )
}
