import { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Container,
  Typography,
  Button,
  IconButton,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  TextField,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Tooltip,
  Chip,
  Checkbox,
  FormGroup,
  FormControlLabel,
} from '@mui/material';
import {
  Add,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Category as CategoryIcon,
} from '@mui/icons-material';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { usePermissionContext } from '../contexts/PermissionContext';
import { useNotification } from '../contexts/NotificationContext';
import { eventsApi } from '../services/events';
import type { VeranstaltungKategorie, GroupInfo } from '../types/events.types';

// ---------------------------------------------------------------------------
// Category Form Dialog
// ---------------------------------------------------------------------------

interface KategorieFormData {
  name: string;
  beschreibung: string;
  farbe: string;
  icon: string;
  alle_gruppen: boolean;
  zielgruppen: string[];
}

const EMPTY_FORM: KategorieFormData = {
  name: '',
  beschreibung: '',
  farbe: '#1976d2',
  icon: '',
  alle_gruppen: false,
  zielgruppen: [],
};

interface KategorieDialogProps {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  editing: VeranstaltungKategorie | null;
  groups: GroupInfo[];
}

function KategorieDialog({ open, onClose, onSaved, editing, groups }: KategorieDialogProps) {
  const notification = useNotification();
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState<KategorieFormData>({ ...EMPTY_FORM });

  useEffect(() => {
    if (!open) return;
    if (editing) {
      setForm({
        name: editing.name,
        beschreibung: editing.beschreibung ?? '',
        farbe: editing.farbe,
        icon: editing.icon ?? '',
        alle_gruppen: editing.alle_gruppen ?? false,
        zielgruppen: editing.alle_gruppen ? [] : (editing.zielgruppen ?? []),
      });
    } else {
      setForm({ ...EMPTY_FORM });
    }
  }, [open, editing]);

  const handleChange = (field: keyof KategorieFormData, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const handleGroupToggle = (groupId: string) => {
    setForm((prev) => ({
      ...prev,
      zielgruppen: prev.zielgruppen.includes(groupId)
        ? prev.zielgruppen.filter((g) => g !== groupId)
        : [...prev.zielgruppen, groupId],
    }));
  };

  const handleSave = async () => {
    if (!form.name.trim()) {
      notification.showError('Name ist erforderlich');
      return;
    }
    setLoading(true);
    try {
      const payload = {
        name: form.name.trim(),
        beschreibung: form.beschreibung.trim() || undefined,
        farbe: form.farbe,
        icon: form.icon.trim() || undefined,
        alle_gruppen: form.alle_gruppen,
        zielgruppen: form.alle_gruppen ? [] : form.zielgruppen,
      };
      if (editing) {
        await eventsApi.updateKategorie(editing.id, payload);
        notification.showSuccess('Kategorie aktualisiert');
      } else {
        await eventsApi.createKategorie(payload);
        notification.showSuccess('Kategorie erstellt');
      }
      onSaved();
      onClose();
    } catch (e: unknown) {
      const msg = (e as any)?.message || 'Fehler beim Speichern';
      notification.showError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>
        {editing ? 'Kategorie bearbeiten' : 'Neue Kategorie'}
      </DialogTitle>
      <DialogContent>
        <Stack spacing={2} sx={{ mt: 1 }}>
          <TextField
            label="Name"
            value={form.name}
            onChange={(e) => handleChange('name', e.target.value)}
            required
            fullWidth
            autoFocus
          />
          <TextField
            label="Beschreibung"
            value={form.beschreibung}
            onChange={(e) => handleChange('beschreibung', e.target.value)}
            multiline
            rows={2}
            fullWidth
          />
          {/* Color picker */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <TextField
              label="Farbe"
              type="color"
              value={form.farbe}
              onChange={(e) => handleChange('farbe', e.target.value)}
              InputLabelProps={{ shrink: true }}
              sx={{ width: 120 }}
              inputProps={{ style: { height: 40, cursor: 'pointer', padding: '4px 8px' } }}
            />
            <Box
              sx={{
                width: 40,
                height: 40,
                borderRadius: 1,
                bgcolor: form.farbe,
                border: '1px solid',
                borderColor: 'divider',
                flexShrink: 0,
              }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
              {form.farbe.toUpperCase()}
            </Typography>
          </Box>
          <TextField
            label="Icon (MUI Icon Name, optional)"
            value={form.icon}
            onChange={(e) => handleChange('icon', e.target.value)}
            fullWidth
            placeholder="z.B. EmojiEvents"
            helperText="Name eines MUI Material Icons"
          />
          {/* alle_gruppen toggle */}
          <FormControlLabel
            control={
              <Checkbox
                checked={form.alle_gruppen}
                onChange={(e) => setForm((prev) => ({
                  ...prev,
                  alle_gruppen: e.target.checked,
                  zielgruppen: e.target.checked ? [] : prev.zielgruppen,
                }))}
                size="small"
              />
            }
            label="Alle Mitglieder"
          />
          {/* Group checkboxes — disabled when alle_gruppen is set */}
          {groups.length > 0 && (
            <Box>
              <Typography variant="subtitle2" sx={{ mb: 0.5 }}>
                Zielgruppen
              </Typography>
              <FormGroup>
                {groups.map((group) => (
                  <FormControlLabel
                    key={group.id}
                    control={
                      <Checkbox
                        checked={form.zielgruppen.includes(group.id)}
                        onChange={() => handleGroupToggle(group.id)}
                        size="small"
                        disabled={form.alle_gruppen}
                      />
                    }
                    label={group.label}
                  />
                ))}
              </FormGroup>
            </Box>
          )}
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Abbrechen</Button>
        <Button variant="contained" onClick={handleSave} disabled={loading}>
          {loading ? <CircularProgress size={20} /> : editing ? 'Speichern' : 'Erstellen'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// Delete Confirm Dialog
// ---------------------------------------------------------------------------

interface DeleteDialogProps {
  open: boolean;
  kategorie: VeranstaltungKategorie | null;
  onClose: () => void;
  onDeleted: () => void;
}

function DeleteDialog({ open, kategorie, onClose, onDeleted }: DeleteDialogProps) {
  const notification = useNotification();
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    if (!kategorie) return;
    setLoading(true);
    try {
      await eventsApi.deleteKategorie(kategorie.id);
      notification.showSuccess('Kategorie gelöscht');
      onDeleted();
      onClose();
    } catch (e: unknown) {
      const msg = (e as any)?.message || 'Fehler beim Löschen';
      notification.showError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Kategorie löschen</DialogTitle>
      <DialogContent>
        <DialogContentText>
          Soll die Kategorie <strong>{kategorie?.name}</strong> wirklich gelöscht werden?
          Bestehende Veranstaltungen behalten ihre Farbzuweisung.
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Abbrechen</Button>
        <Button variant="contained" color="error" onClick={handleDelete} disabled={loading}>
          {loading ? <CircularProgress size={20} /> : 'Löschen'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// ---------------------------------------------------------------------------
// Main Page
// ---------------------------------------------------------------------------

export default function VeranstaltungKategorien() {
  const { hasPermission } = usePermissionContext();

  const canManage = hasPermission('kalender:create');

  const [kategorien, setKategorien] = useState<VeranstaltungKategorie[]>([]);
  const [groups, setGroups] = useState<GroupInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Form dialog
  const [formOpen, setFormOpen] = useState(false);
  const [editingKat, setEditingKat] = useState<VeranstaltungKategorie | null>(null);

  // Delete dialog
  const [deleteTarget, setDeleteTarget] = useState<VeranstaltungKategorie | null>(null);

  const loadKategorien = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [data, groupData] = await Promise.all([
        eventsApi.getKategorien(),
        eventsApi.getGroups(),
      ]);
      setKategorien(data);
      setGroups(groupData);
    } catch (e: unknown) {
      const msg = (e as any)?.message || 'Fehler beim Laden der Kategorien';
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadKategorien();
  }, [loadKategorien]);

  return (
    <DashboardLayout>
      <Container maxWidth="lg" sx={{ py: 3 }}>
        {/* Header */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            flexWrap: 'wrap',
            gap: 1,
            mb: 3,
          }}
        >
          <CategoryIcon color="primary" />
          <Typography variant="h5" sx={{ flexGrow: 1, fontWeight: 700 }}>
            Veranstaltungskategorien
          </Typography>
          {canManage && (
            <Button
              startIcon={<Add />}
              variant="contained"
              onClick={() => { setEditingKat(null); setFormOpen(true); }}
            >
              Neue Kategorie
            </Button>
          )}
        </Box>

        {/* Error */}
        {error && (
          <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
            {error}
          </Alert>
        )}

        {/* Loading */}
        {loading && (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
            <CircularProgress />
          </Box>
        )}

        {/* Table */}
        {!loading && !error && (
          <TableContainer component={Paper} elevation={1}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 700 }}>Farbe</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Name</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Beschreibung</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Icon</TableCell>
                  <TableCell sx={{ fontWeight: 700 }}>Gruppen</TableCell>
                  {canManage && <TableCell align="right" sx={{ fontWeight: 700 }}>Aktionen</TableCell>}
                </TableRow>
              </TableHead>
              <TableBody>
                {kategorien.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={canManage ? 6 : 5} align="center" sx={{ py: 4 }}>
                      <Typography variant="body2" color="text.secondary">
                        Noch keine Kategorien vorhanden.
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  kategorien.map((kat) => (
                    <TableRow
                      key={kat.id}
                      hover
                      sx={{ '&:last-child td': { border: 0 } }}
                    >
                      {/* Color swatch */}
                      <TableCell>
                        <Tooltip title={kat.farbe.toUpperCase()}>
                          <Box
                            sx={{
                              width: 28,
                              height: 28,
                              borderRadius: 1,
                              bgcolor: kat.farbe,
                              border: '1px solid',
                              borderColor: 'divider',
                            }}
                          />
                        </Tooltip>
                      </TableCell>

                      {/* Name */}
                      <TableCell>
                        <Chip
                          label={kat.name}
                          size="small"
                          sx={{
                            bgcolor: kat.farbe,
                            color: 'white',
                            fontWeight: 600,
                          }}
                        />
                      </TableCell>

                      {/* Description */}
                      <TableCell>
                        <Typography variant="body2" color="text.secondary">
                          {kat.beschreibung ?? '—'}
                        </Typography>
                      </TableCell>

                      {/* Icon */}
                      <TableCell>
                        <Typography variant="body2" sx={{ fontFamily: 'monospace', fontSize: '0.8rem' }}>
                          {kat.icon ?? '—'}
                        </Typography>
                      </TableCell>

                      {/* Gruppen */}
                      <TableCell>
                        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                          {kat.alle_gruppen ? (
                            <Chip
                              label="Alle Mitglieder"
                              size="small"
                              color="primary"
                              variant="outlined"
                              sx={{ fontSize: '0.75rem' }}
                            />
                          ) : (kat.zielgruppen ?? []).length === 0
                            ? <Typography variant="body2" color="text.secondary">—</Typography>
                            : (kat.zielgruppen ?? []).map((gId) => {
                                const group = groups.find((g) => g.id === gId);
                                return (
                                  <Chip
                                    key={gId}
                                    label={group?.label ?? gId}
                                    size="small"
                                    variant="outlined"
                                    sx={{ fontSize: '0.75rem' }}
                                  />
                                );
                              })
                          }
                        </Box>
                      </TableCell>

                      {/* Actions */}
                      {canManage && (
                        <TableCell align="right">
                          <Stack direction="row" spacing={0.5} justifyContent="flex-end">
                            <Tooltip title="Bearbeiten">
                              <IconButton
                                size="small"
                                onClick={() => { setEditingKat(kat); setFormOpen(true); }}
                              >
                                <EditIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Löschen">
                              <IconButton
                                size="small"
                                color="error"
                                onClick={() => setDeleteTarget(kat)}
                              >
                                <DeleteIcon fontSize="small" />
                              </IconButton>
                            </Tooltip>
                          </Stack>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}

        {/* Create/Edit Dialog */}
        <KategorieDialog
          open={formOpen}
          onClose={() => { setFormOpen(false); setEditingKat(null); }}
          onSaved={loadKategorien}
          editing={editingKat}
          groups={groups}
        />

        {/* Delete Confirm Dialog */}
        <DeleteDialog
          open={Boolean(deleteTarget)}
          kategorie={deleteTarget}
          onClose={() => setDeleteTarget(null)}
          onDeleted={loadKategorien}
        />
      </Container>
    </DashboardLayout>
  );
}
