import { useState } from 'react';
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Paper,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from '@mui/material';
import { Add, DeleteForever as DeleteForeverIcon, Edit as EditIcon } from '@mui/icons-material';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { eventsApi } from '../../services/events';
import { usePermissionContext } from '../../contexts/PermissionContext';
import { useNotification } from '../../contexts/NotificationContext';
import type { VeranstaltungKategorie } from '../../types/events.types';

export default function ModuleSettingsKalender() {
  const { isFeatureEnabled } = usePermissionContext();
  const notification = useNotification();
  const queryClient = useQueryClient();

  const { data: kategorien = [], isLoading, isError } = useQuery({
    queryKey: ['kalender-kategorien'],
    queryFn: eventsApi.getKategorien,
  });

  const [editingKat, setEditingKat] = useState<VeranstaltungKategorie | null>(null);
  const [newKatOpen, setNewKatOpen] = useState(false);
  const [newKatForm, setNewKatForm] = useState({ name: '', farbe: '#1976d2', beschreibung: '' });
  const [saving, setSaving] = useState(false);

  const reload = () => queryClient.invalidateQueries({ queryKey: ['kalender-kategorien'] });

  const handleCreate = async () => {
    if (!newKatForm.name.trim()) return;
    setSaving(true);
    try {
      await eventsApi.createKategorie({ name: newKatForm.name.trim(), farbe: newKatForm.farbe, beschreibung: newKatForm.beschreibung || undefined });
      notification.showSuccess('Kategorie erstellt');
      setNewKatOpen(false);
      setNewKatForm({ name: '', farbe: '#1976d2', beschreibung: '' });
      reload();
    } catch { notification.showError('Fehler beim Erstellen'); }
    finally { setSaving(false); }
  };

  const handleUpdate = async () => {
    if (!editingKat) return;
    setSaving(true);
    try {
      await eventsApi.updateKategorie(editingKat.id, { name: editingKat.name, farbe: editingKat.farbe, beschreibung: editingKat.beschreibung ?? undefined });
      notification.showSuccess('Kategorie gespeichert');
      setEditingKat(null);
      reload();
    } catch { notification.showError('Fehler beim Speichern'); }
    finally { setSaving(false); }
  };

  const handleDelete = async (id: string) => {
    try {
      await eventsApi.deleteKategorie(id);
      notification.showSuccess('Kategorie gelöscht');
      reload();
    } catch { notification.showError('Fehler beim Löschen'); }
  };

  if (!isFeatureEnabled('kalender')) {
    return <Alert severity="warning">Im Wartungsmodus</Alert>;
  }

  if (isLoading) {
    return (
      <Box>
        <Skeleton variant="rectangular" height={40} sx={{ mb: 2 }} />
        <Skeleton variant="rectangular" height={200} />
      </Box>
    );
  }

  if (isError) {
    return <Alert severity="error">Fehler beim Laden der Kategorien</Alert>;
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6" sx={{ flexGrow: 1 }}>Veranstaltungskategorien</Typography>
        <Button startIcon={<Add />} variant="contained" size="small" onClick={() => setNewKatOpen(true)}>
          Neue Kategorie
        </Button>
      </Box>

      <TableContainer component={Paper} variant="outlined">
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>Farbe</TableCell>
              <TableCell>Name</TableCell>
              <TableCell>Beschreibung</TableCell>
              <TableCell align="right">Aktionen</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {kategorien.map((k) => (
              <TableRow key={k.id}>
                <TableCell>
                  <Box sx={{ width: 24, height: 24, borderRadius: '50%', bgcolor: k.farbe, border: '1px solid', borderColor: 'divider' }} />
                </TableCell>
                <TableCell>{k.name}</TableCell>
                <TableCell>{k.beschreibung ?? '—'}</TableCell>
                <TableCell align="right">
                  <IconButton size="small" onClick={() => setEditingKat({ ...k })}>
                    <EditIcon fontSize="small" />
                  </IconButton>
                  <IconButton size="small" color="error" onClick={() => handleDelete(k.id)}>
                    <DeleteForeverIcon fontSize="small" />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
            {kategorien.length === 0 && (
              <TableRow>
                <TableCell colSpan={4} sx={{ textAlign: 'center', py: 3, color: 'text.secondary' }}>
                  Noch keine Kategorien vorhanden
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Edit dialog */}
      <Dialog open={Boolean(editingKat)} onClose={() => setEditingKat(null)} maxWidth="xs" fullWidth>
        <DialogTitle>Kategorie bearbeiten</DialogTitle>
        <DialogContent>
          <Stack spacing={2} sx={{ mt: 1 }}>
            <TextField label="Name" value={editingKat?.name ?? ''} onChange={(e) => setEditingKat((k) => k ? { ...k, name: e.target.value } : k)} fullWidth required />
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Typography variant="body2">Farbe</Typography>
              <input type="color" value={editingKat?.farbe ?? '#1976d2'} onChange={(e) => setEditingKat((k) => k ? { ...k, farbe: e.target.value } : k)} style={{ width: 40, height: 36, border: 'none', cursor: 'pointer', borderRadius: 4 }} />
              <Typography variant="body2" color="text.secondary">{editingKat?.farbe}</Typography>
            </Box>
            <TextField label="Beschreibung" value={editingKat?.beschreibung ?? ''} onChange={(e) => setEditingKat((k) => k ? { ...k, beschreibung: e.target.value || null } : k)} fullWidth multiline rows={2} />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEditingKat(null)}>Abbrechen</Button>
          <Button variant="contained" onClick={handleUpdate} disabled={saving || !editingKat?.name.trim()}>
            {saving ? <CircularProgress size={20} /> : 'Speichern'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* New category dialog */}
      <Dialog open={newKatOpen} onClose={() => setNewKatOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>Neue Kategorie</DialogTitle>
        <DialogContent>
          <Stack spacing={2} sx={{ mt: 1 }}>
            <TextField label="Name" value={newKatForm.name} onChange={(e) => setNewKatForm((f) => ({ ...f, name: e.target.value }))} fullWidth required />
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Typography variant="body2">Farbe</Typography>
              <input type="color" value={newKatForm.farbe} onChange={(e) => setNewKatForm((f) => ({ ...f, farbe: e.target.value }))} style={{ width: 40, height: 36, border: 'none', cursor: 'pointer', borderRadius: 4 }} />
              <Typography variant="body2" color="text.secondary">{newKatForm.farbe}</Typography>
            </Box>
            <TextField label="Beschreibung" value={newKatForm.beschreibung} onChange={(e) => setNewKatForm((f) => ({ ...f, beschreibung: e.target.value }))} fullWidth multiline rows={2} />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setNewKatOpen(false)}>Abbrechen</Button>
          <Button variant="contained" onClick={handleCreate} disabled={saving || !newKatForm.name.trim()}>
            {saving ? <CircularProgress size={20} /> : 'Erstellen'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
