'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import { AlertTriangle, Eye, EyeOff, Trash2, Plus, Loader2, GripVertical } from 'lucide-react'

interface SomaTemplate {
  id: string
  label: string
  sortOrder: number
  isActive: boolean
}

export function SomaTab() {
  const { toast } = useToast()
  const [somaTemplates, setSomaTemplates] = useState<SomaTemplate[]>([])
  const [newSomaLabel, setNewSomaLabel] = useState('')
  const [somaLoading, setSomaLoading] = useState(false)

  const fetchSomaTemplates = async () => {
    setSomaLoading(true)
    try {
      const res = await fetch('/api/tenant/soma-templates')
      if (res.ok) {
        const data = await res.json()
        setSomaTemplates(data.templates || [])
      }
    } catch {}
    setSomaLoading(false)
  }

  useEffect(() => {
    fetchSomaTemplates()
  }, [])

  const handleAdd = async () => {
    if (!newSomaLabel.trim()) return
    try {
      await fetch('/api/tenant/soma-templates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ label: newSomaLabel.trim(), sortOrder: somaTemplates.length }),
      })
      setNewSomaLabel('')
      fetchSomaTemplates()
      toast({ title: 'SOMA-Vorlage hinzugefügt' })
    } catch {}
  }

  return (
    <div className="border rounded-lg p-6">
      <h3 className="font-semibold text-lg mb-2 flex items-center gap-2">
        <AlertTriangle className="w-5 h-5 text-red-600" />
        SOMA-Checkliste verwalten
      </h3>
      <p className="text-sm text-muted-foreground mb-4">
        Definiere die Sofortmassnahmen (SOMA), die bei jedem neuen Einsatz als Checkliste erscheinen.
        Bestehende Einsätze werden nicht verändert.
      </p>

      {somaLoading ? (
        <div className="flex items-center gap-2 py-4 text-muted-foreground">
          <Loader2 className="w-4 h-4 animate-spin" /> Laden...
        </div>
      ) : (
        <>
          {/* Template list */}
          <div className="border rounded-lg divide-y">
            {somaTemplates.length === 0 ? (
              <div className="px-4 py-6 text-center text-muted-foreground text-sm">
                Keine SOMA-Vorlagen definiert. Neue Einsätze starten ohne Checkliste.
              </div>
            ) : somaTemplates.map((tpl, idx) => (
              <div key={tpl.id} className={`flex items-center gap-3 px-4 py-2.5 ${!tpl.isActive ? 'opacity-50' : ''}`}>
                <GripVertical className="w-4 h-4 text-muted-foreground/40 shrink-0" />
                <span className="text-sm font-medium flex-1">{tpl.label}</span>
                <span className="text-xs text-muted-foreground">#{idx + 1}</span>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 px-2"
                  onClick={async () => {
                    try {
                      await fetch('/api/tenant/soma-templates', {
                        method: 'PATCH',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ updates: [{ id: tpl.id, isActive: !tpl.isActive }] }),
                      })
                      fetchSomaTemplates()
                    } catch {}
                  }}
                >
                  {tpl.isActive ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 px-2 text-destructive hover:text-destructive"
                  onClick={async () => {
                    if (!confirm(`"${tpl.label}" wirklich löschen?`)) return
                    try {
                      await fetch('/api/tenant/soma-templates', {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: tpl.id }),
                      })
                      fetchSomaTemplates()
                      toast({ title: 'SOMA-Vorlage gelöscht' })
                    } catch {}
                  }}
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </Button>
              </div>
            ))}
          </div>

          {/* Add new */}
          <div className="flex gap-2 mt-4">
            <Input
              placeholder="Neue Sofortmassnahme..."
              value={newSomaLabel}
              onChange={e => setNewSomaLabel(e.target.value)}
              onKeyDown={e => {
                if (e.key === 'Enter' && newSomaLabel.trim()) {
                  e.preventDefault()
                  handleAdd()
                }
              }}
              className="flex-1"
            />
            <Button disabled={!newSomaLabel.trim()} onClick={handleAdd}>
              <Plus className="w-4 h-4 mr-1" /> Hinzufügen
            </Button>
          </div>

          <p className="text-xs text-muted-foreground mt-3">
            {somaTemplates.filter(t => t.isActive).length} aktiv / {somaTemplates.length} gesamt —
            Nur aktive Vorlagen erscheinen bei neuen Einsätzen.
          </p>
        </>
      )}
    </div>
  )
}
