'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from '@/components/ui/dialog'
import {
  ArrowUp, ArrowDown, Plus, Trash2, Loader2, Blocks, X,
} from 'lucide-react'
import { MODULE_PRESETS, type CockpitModule, type ModuleColumn, type ModuleColumnType } from '@/lib/modules'

interface ModuleManagerDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  modules: CockpitModule[]
  onSaved: (modules: CockpitModule[]) => void
}

/**
 * "Module verwalten" — der Baukasten:
 * Module ein-/ausschalten, Reihenfolge ändern, eigene Tabellen-Module
 * aus Vorlagen erstellen (Checkliste, Atemschutz, Kräfte, Lagemeldungen, leer).
 * Gespeichert wird pro Mandant (gilt für alle Einsätze).
 */
export function ModuleManagerDialog({ open, onOpenChange, modules, onSaved }: ModuleManagerDialogProps) {
  const [working, setWorking] = useState<CockpitModule[]>(modules)
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState('')

  // Neues Modul aus Vorlage
  const [showAdd, setShowAdd] = useState(false)
  const [presetKey, setPresetKey] = useState(MODULE_PRESETS[0].key)
  const [newName, setNewName] = useState('')
  const [newColumns, setNewColumns] = useState<ModuleColumn[]>(MODULE_PRESETS[0].columns)

  useEffect(() => {
    if (open) {
      setWorking(modules)
      setError('')
      setShowAdd(false)
    }
  }, [open, modules])

  const move = (idx: number, dir: -1 | 1) => {
    const next = [...working]
    const target = idx + dir
    if (target < 0 || target >= next.length) return
    ;[next[idx], next[target]] = [next[target], next[idx]]
    setWorking(next.map((m, i) => ({ ...m, sortOrder: i })))
  }

  const toggle = (idx: number) => {
    setWorking(prev => prev.map((m, i) => i === idx ? { ...m, enabled: !m.enabled } : m))
  }

  const removeCustom = (idx: number) => {
    setWorking(prev => prev.filter((_, i) => i !== idx).map((m, i) => ({ ...m, sortOrder: i })))
  }

  const selectPreset = (key: string) => {
    const preset = MODULE_PRESETS.find(p => p.key === key)!
    setPresetKey(key)
    setNewName(preset.key === 'leer' ? '' : preset.name)
    setNewColumns(preset.columns)
  }

  const addModule = () => {
    const preset = MODULE_PRESETS.find(p => p.key === presetKey)!
    const name = newName.trim() || preset.name
    const mod: CockpitModule = {
      id: `custom-${Date.now().toString(36)}`,
      type: 'table',
      name,
      icon: preset.icon,
      slot: preset.slot,
      enabled: true,
      sortOrder: working.length,
      columns: newColumns.filter(c => c.label.trim()),
    }
    if (!mod.columns || mod.columns.length === 0) return
    setWorking(prev => [...prev, mod])
    setShowAdd(false)
    setNewName('')
  }

  const updateColumn = (idx: number, patch: Partial<ModuleColumn>) => {
    setNewColumns(prev => prev.map((c, i) => i === idx ? { ...c, ...patch } : c))
  }

  const addColumn = () => {
    if (newColumns.length >= 8) return
    setNewColumns(prev => [...prev, { key: `col${prev.length}-${Date.now().toString(36).slice(-4)}`, label: '', type: 'text' }])
  }

  const removeColumn = (idx: number) => {
    setNewColumns(prev => prev.filter((_, i) => i !== idx))
  }

  const save = async () => {
    setIsSaving(true)
    setError('')
    try {
      const res = await fetch('/api/tenant/modules', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ modules: working }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Speichern fehlgeschlagen')
      onSaved(data.modules)
      onOpenChange(false)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
    } finally {
      setIsSaving(false)
    }
  }

  const COLUMN_TYPES: { value: ModuleColumnType; label: string }[] = [
    { value: 'text', label: 'Text' },
    { value: 'check', label: 'Haken' },
    { value: 'time', label: 'Zeit (auto)' },
  ]

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Blocks className="w-5 h-5" />
            Cockpit-Module verwalten
          </DialogTitle>
        </DialogHeader>

        <p className="text-xs text-muted-foreground -mt-2">
          Stelle das Einsatz-Cockpit für deine Feuerwehr zusammen. Gilt für alle Einsätze deiner Organisation.
        </p>

        {/* Modul-Liste */}
        <div className="space-y-1.5">
          {working.map((m, idx) => (
            <div key={m.id} className={`flex items-center gap-2 rounded-lg border px-2.5 py-2 ${m.enabled ? 'bg-card' : 'bg-muted/40 opacity-60'}`}>
              {/* An/aus */}
              <button
                onClick={() => toggle(idx)}
                className={`relative w-9 h-5 rounded-full transition-colors shrink-0 ${m.enabled ? 'bg-green-500' : 'bg-muted-foreground/30'}`}
                title={m.enabled ? 'Deaktivieren' : 'Aktivieren'}
              >
                <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-all ${m.enabled ? 'left-[18px]' : 'left-0.5'}`} />
              </button>

              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium truncate">{m.name}</p>
                <p className="text-[10px] text-muted-foreground">
                  {m.type === 'table' ? `Eigenes Modul · ${m.columns?.length || 0} Spalten` : 'Eingebaut'}
                  {' · '}{m.slot === 'main' ? 'Hauptbereich' : 'Seitenspalte'}
                </p>
              </div>

              <div className="flex items-center gap-0.5 shrink-0">
                <button onClick={() => move(idx, -1)} disabled={idx === 0} className="p-1 text-muted-foreground hover:text-foreground disabled:opacity-30" title="Nach oben">
                  <ArrowUp className="w-3.5 h-3.5" />
                </button>
                <button onClick={() => move(idx, 1)} disabled={idx === working.length - 1} className="p-1 text-muted-foreground hover:text-foreground disabled:opacity-30" title="Nach unten">
                  <ArrowDown className="w-3.5 h-3.5" />
                </button>
                {m.type === 'table' && (
                  <button onClick={() => removeCustom(idx)} className="p-1 text-muted-foreground hover:text-destructive" title="Modul löschen (Daten bleiben in der DB)">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Neues Modul */}
        {!showAdd ? (
          <Button variant="outline" size="sm" onClick={() => { selectPreset(MODULE_PRESETS[0].key); setShowAdd(true) }} className="w-full">
            <Plus className="w-4 h-4 mr-1.5" /> Modul hinzufügen
          </Button>
        ) : (
          <div className="rounded-lg border p-3 space-y-3 bg-muted/20">
            <div className="flex items-center justify-between">
              <p className="text-sm font-semibold">Neues Modul</p>
              <button onClick={() => setShowAdd(false)} className="text-muted-foreground hover:text-foreground"><X className="w-4 h-4" /></button>
            </div>

            {/* Vorlagen */}
            <div className="grid grid-cols-2 gap-1.5">
              {MODULE_PRESETS.map(p => (
                <button
                  key={p.key}
                  onClick={() => selectPreset(p.key)}
                  className={`text-left rounded-md border-2 px-2 py-1.5 transition-colors ${
                    presetKey === p.key ? 'border-primary bg-primary/5' : 'border-border hover:border-muted-foreground'
                  }`}
                  title={p.description}
                >
                  <p className="text-xs font-medium">{p.name}</p>
                  <p className="text-[10px] text-muted-foreground line-clamp-1">{p.description}</p>
                </button>
              ))}
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs">Name</Label>
              <Input value={newName} onChange={e => setNewName(e.target.value)} placeholder="z.B. Atemschutz Zug 1" className="h-8 text-sm" />
            </div>

            {/* Spalten-Editor */}
            <div className="space-y-1.5">
              <Label className="text-xs">Spalten</Label>
              {newColumns.map((c, i) => (
                <div key={c.key} className="flex items-center gap-1.5">
                  <Input
                    value={c.label}
                    onChange={e => updateColumn(i, { label: e.target.value })}
                    placeholder={`Spalte ${i + 1}`}
                    className="h-7 text-xs flex-1"
                  />
                  <select
                    value={c.type}
                    onChange={e => updateColumn(i, { type: e.target.value as ModuleColumnType })}
                    className="h-7 text-xs rounded-md border border-input bg-background px-1.5"
                  >
                    {COLUMN_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                  </select>
                  <button onClick={() => removeColumn(i)} disabled={newColumns.length <= 1} className="p-1 text-muted-foreground hover:text-destructive disabled:opacity-30">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              ))}
              {newColumns.length < 8 && (
                <button onClick={addColumn} className="text-xs text-primary hover:underline flex items-center gap-1">
                  <Plus className="w-3 h-3" /> Spalte hinzufügen
                </button>
              )}
            </div>

            <Button size="sm" onClick={addModule} disabled={newColumns.filter(c => c.label.trim()).length === 0} className="w-full">
              <Plus className="w-4 h-4 mr-1" /> Modul erstellen
            </Button>
          </div>
        )}

        {error && <p className="text-sm text-destructive">{error}</p>}

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>Abbrechen</Button>
          <Button onClick={save} disabled={isSaving}>
            {isSaving ? <><Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> Speichern…</> : 'Speichern'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
