'use client'

import { useState, useEffect, useCallback } 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 { useToast } from '@/components/ui/use-toast'
import { FolderPlus, Pencil, Trash2 } from 'lucide-react'
import type { IconCategory } from './admin-constants'

export function CategoriesTab() {
  const { toast } = useToast()
  const [categories, setCategories] = useState<IconCategory[]>([])

  const [isCategoryDialogOpen, setIsCategoryDialogOpen] = useState(false)
  const [editingCategory, setEditingCategory] = useState<IconCategory | null>(null)
  const [categoryName, setCategoryName] = useState('')
  const [categoryDescription, setCategoryDescription] = useState('')

  const fetchCategories = useCallback(async () => {
    try {
      const res = await fetch('/api/admin/categories')
      if (res.ok) setCategories((await res.json()).categories || [])
    } catch (e) {
      console.error('Error fetching categories:', e)
    }
  }, [])

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

  const handleSaveCategory = async () => {
    try {
      const url = editingCategory ? `/api/admin/categories/${editingCategory.id}` : '/api/admin/categories'
      const method = editingCategory ? 'PATCH' : 'POST'
      const res = await fetch(url, {
        method, headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: categoryName, description: categoryDescription || null }),
      })
      if (res.ok) {
        toast({ title: editingCategory ? 'Kategorie aktualisiert' : 'Kategorie erstellt' })
        setIsCategoryDialogOpen(false); setEditingCategory(null); setCategoryName(''); setCategoryDescription('')
        fetchCategories()
      } else {
        const err = await res.json(); throw new Error(err.error)
      }
    } catch (error) {
      toast({ title: 'Fehler', description: error instanceof Error ? error.message : 'Fehler', variant: 'destructive' })
    }
  }

  const handleDeleteCategory = async (id: string) => {
    if (!confirm('Kategorie wirklich löschen?')) return
    try {
      const res = await fetch(`/api/admin/categories/${id}`, { method: 'DELETE' })
      if (res.ok) { toast({ title: 'Kategorie gelöscht' }); fetchCategories() }
    } catch { toast({ title: 'Fehler', variant: 'destructive' }) }
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <p className="text-sm text-muted-foreground">{categories.length} Kategorie(n)</p>
        <Button onClick={() => { setEditingCategory(null); setCategoryName(''); setCategoryDescription(''); setIsCategoryDialogOpen(true) }}>
          <FolderPlus className="w-4 h-4 mr-2" />
          Neue Kategorie
        </Button>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {categories.map(cat => (
          <div key={cat.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
            <div className="flex items-start justify-between">
              <div>
                <h3 className="font-medium">{cat.name}</h3>
                {cat.description && <p className="text-sm text-muted-foreground mt-1">{cat.description}</p>}
                <p className="text-xs text-muted-foreground mt-2">{cat._count?.icons || 0} Symbol(e) · Reihenfolge: {cat.sortOrder}</p>
              </div>
              <div className="flex gap-1">
                <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => {
                  setEditingCategory(cat); setCategoryName(cat.name); setCategoryDescription(cat.description || ''); setIsCategoryDialogOpen(true)
                }}>
                  <Pencil className="w-4 h-4" />
                </Button>
                <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDeleteCategory(cat.id)}>
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Category Dialog */}
      <Dialog open={isCategoryDialogOpen} onOpenChange={setIsCategoryDialogOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>{editingCategory ? 'Kategorie bearbeiten' : 'Neue Kategorie'}</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div><Label>Name</Label><Input value={categoryName} onChange={e => setCategoryName(e.target.value)} placeholder="z.B. Fahrzeuge" /></div>
            <div><Label>Beschreibung (optional)</Label><Input value={categoryDescription} onChange={e => setCategoryDescription(e.target.value)} placeholder="Kurze Beschreibung" /></div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsCategoryDialogOpen(false)}>Abbrechen</Button>
            <Button onClick={handleSaveCategory} disabled={!categoryName.trim()}>Speichern</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
