import React, { useState, useEffect } from 'react';
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Alert,
  Autocomplete,
  Badge,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormControlLabel,
  FormLabel,
  IconButton,
  InputLabel,
  List,
  ListItemButton,
  ListItemText,
  MenuItem,
  Paper,
  Radio,
  RadioGroup,
  Select,
  Switch,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from '@mui/material';
import {
  Add as AddIcon,
  BuildCircle,
  Delete as DeleteIcon,
  DirectionsCar,
  Edit as EditIcon,
  ExpandMore,
  PlayArrow,
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate, useSearchParams } from 'react-router-dom';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { TabPanel, DataTable } from '../components/templates';
import type { Column } from '../components/templates';
import { usePermissionContext } from '../contexts/PermissionContext';
import { useNotification } from '../contexts/NotificationContext';
import { checklistenApi } from '../services/checklisten';
import { fahrzeugTypenApi } from '../services/fahrzeugTypen';
import { ausruestungTypenApi } from '../services/ausruestungTypen';
import { vehiclesApi } from '../services/vehicles';
import { equipmentApi } from '../services/equipment';
import {
  CHECKLIST_STATUS_LABELS,
  CHECKLIST_STATUS_COLORS,
} from '../types/checklist.types';
import type {
  ChecklistVorlage,
  ChecklistVorlageItem,
  ChecklistAusfuehrung,
  ChecklistOverviewItem,
  ChecklistOverviewChecklist,
  FahrzeugTyp,
  CreateVorlagePayload,
  UpdateVorlagePayload,
  CreateVorlageItemPayload,
} from '../types/checklist.types';
import type { AusruestungTyp } from '../services/ausruestungTypen';

// ── Helpers ──

const formatDate = (iso?: string) =>
  iso ? new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' }) : '–';

const INTERVALL_LABELS: Record<string, string> = {
  weekly: 'Wöchentlich',
  monthly: 'Monatlich',
  quarterly: 'Quartalsweise',
  halfyearly: 'Halbjährlich',
  yearly: 'Jährlich',
  custom: 'Benutzerdefiniert',
};

type AssignmentType = 'global' | 'fahrzeug_typ' | 'fahrzeug' | 'ausruestung_typ' | 'ausruestung';

function getAssignmentType(v: ChecklistVorlage): AssignmentType {
  if (v.fahrzeug_ids?.length) return 'fahrzeug';
  if (v.fahrzeug_typ_ids?.length) return 'fahrzeug_typ';
  if (v.ausruestung_ids?.length) return 'ausruestung';
  if (v.ausruestung_typ_ids?.length) return 'ausruestung_typ';
  return 'global';
}

function getAssignmentLabel(v: ChecklistVorlage): string {
  if (v.fahrzeug_ids?.length) return v.fahrzeug_names?.length ? `Fahrzeug: ${v.fahrzeug_names.join(', ')}` : 'Fahrzeug (direkt)';
  if (v.fahrzeug_typ_ids?.length) return v.fahrzeug_typ_names?.length ? `Fahrzeugtyp: ${v.fahrzeug_typ_names.join(', ')}` : 'Fahrzeugtyp';
  if (v.ausruestung_ids?.length) return v.ausruestung_names?.length ? `Ausrüstung: ${v.ausruestung_names.join(', ')}` : 'Ausrüstung (direkt)';
  if (v.ausruestung_typ_ids?.length) return v.ausruestung_typ_names?.length ? `Ausrüstungstyp: ${v.ausruestung_typ_names.join(', ')}` : 'Ausrüstungstyp';
  return 'Global';
}

function getDueColor(nextDue?: string | null, intervall?: string | null): 'error' | 'warning' | 'success' | 'default' {
  if (!nextDue) return intervall ? 'warning' : 'default'; // has recurrence but never run → warn; no recurrence → neutral
  const daysUntil = Math.ceil((new Date(nextDue).getTime() - Date.now()) / 86400000);
  if (daysUntil < 0) return 'error';
  if (daysUntil <= 3) return 'warning';
  return 'success';
}

function getDueLabel(nextDue?: string | null, intervall?: string | null): string {
  if (!nextDue) return intervall ? 'Noch nie ausgeführt' : 'Manuell';
  const daysUntil = Math.ceil((new Date(nextDue).getTime() - Date.now()) / 86400000);
  if (daysUntil < 0) return `${Math.abs(daysUntil)}d überfällig`;
  if (daysUntil === 0) return 'Heute fällig';
  return `in ${daysUntil}d fällig`;
}

// ══════════════════════════════════════════════════════════════════════════════
// Component
// ══════════════════════════════════════════════════════════════════════════════

export default function Checklisten() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const queryClient = useQueryClient();
  const { hasPermission } = usePermissionContext();
  const { showSuccess, showError } = useNotification();

  const canManageTemplates = hasPermission('checklisten:manage_templates');
  const canExecute = hasPermission('checklisten:execute');

  // Tabs: 0=Übersicht, 1=Vorlagen (if perm), 2=Historie
  const manageTabs = canManageTemplates ? 1 : 0;
  const TAB_COUNT = 2 + manageTabs;

  const [tab, setTab] = useState(() => {
    const t = Number(searchParams.get('tab'));
    return t >= 0 && t < TAB_COUNT ? t : 0;
  });
  useEffect(() => {
    const t = Number(searchParams.get('tab'));
    if (t >= 0 && t < TAB_COUNT) setTab(t);
  }, [searchParams, TAB_COUNT]);

  // ── Queries ──
  const { data: overview, isLoading: overviewLoading } = useQuery({
    queryKey: ['checklisten', 'overview'],
    queryFn: checklistenApi.getOverview,
    refetchInterval: 60000,
  });

  const { data: vorlagen = [], isLoading: vorlagenLoading } = useQuery({
    queryKey: ['checklisten-vorlagen'],
    queryFn: () => checklistenApi.getVorlagen(),
    enabled: canManageTemplates,
  });

  const { data: fahrzeugTypen = [] } = useQuery({
    queryKey: ['fahrzeug-typen'],
    queryFn: fahrzeugTypenApi.getAll,
    enabled: canManageTemplates,
  });

  const { data: executions = [], isLoading: executionsLoading } = useQuery({
    queryKey: ['checklisten-ausfuehrungen'],
    queryFn: () => checklistenApi.getExecutions(),
  });

  // ── Tab indices ──
  const vorlagenTabIdx = canManageTemplates ? 1 : -1;
  const historieTabIdx = canManageTemplates ? 2 : 1;

  return (
    <DashboardLayout>
      <Typography variant="h4" sx={{ mb: 3 }}>Checklisten</Typography>

      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs
          value={tab}
          onChange={(_e, v) => { setTab(v); navigate(`/checklisten?tab=${v}`, { replace: true }); }}
          variant="scrollable"
          scrollButtons="auto"
        >
          <Tab label="Übersicht" />
          {canManageTemplates && <Tab label="Vorlagen" />}
          <Tab label="Historie" />
        </Tabs>
      </Box>

      {/* Tab 0: Übersicht */}
      <TabPanel value={tab} index={0}>
        <OverviewTab
          overview={overview}
          loading={overviewLoading}
          canExecute={canExecute}
          navigate={navigate}
        />
      </TabPanel>

      {/* Tab 1: Vorlagen (templates) */}
      {canManageTemplates && (
        <TabPanel value={tab} index={vorlagenTabIdx}>
          <VorlagenTab
            vorlagen={vorlagen}
            loading={vorlagenLoading}
            fahrzeugTypen={fahrzeugTypen}
            queryClient={queryClient}
            showSuccess={showSuccess}
            showError={showError}
          />
        </TabPanel>
      )}

      {/* Tab 2: Historie */}
      <TabPanel value={tab} index={historieTabIdx}>
        <HistorieTab
          executions={executions}
          loading={executionsLoading}
          navigate={navigate}
        />
      </TabPanel>
    </DashboardLayout>
  );
}

// ══════════════════════════════════════════════════════════════════════════════
// Overview Tab
// ══════════════════════════════════════════════════════════════════════════════

interface OverviewTabProps {
  overview?: { vehicles: ChecklistOverviewItem[]; equipment: ChecklistOverviewItem[] };
  loading: boolean;
  canExecute: boolean;
  navigate: ReturnType<typeof useNavigate>;
}

function OverviewTab({ overview, loading, canExecute, navigate }: OverviewTabProps) {
  if (loading) {
    return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;
  }

  const vehicles = overview?.vehicles ?? [];
  const equipment = overview?.equipment ?? [];

  if (vehicles.length === 0 && equipment.length === 0) {
    return <Alert severity="info" sx={{ mt: 1 }}>Keine Checklisten zugewiesen</Alert>;
  }

  const renderChecklistRow = (cl: ChecklistOverviewChecklist, itemId: string, type: 'fahrzeug' | 'ausruestung', index: number) => {
    const color = getDueColor(cl.next_due, cl.intervall);
    const label = getDueLabel(cl.next_due, cl.intervall);
    const param = type === 'fahrzeug' ? `fahrzeug=${itemId}` : `ausruestung=${itemId}`;
    return (
      <ListItemButton
        key={cl.vorlage_id}
        onClick={() => canExecute && navigate(`/checklisten/ausfuehrung/new?${param}&vorlage=${cl.vorlage_id}`)}
        sx={{
          py: 0.75,
          px: 2,
          bgcolor: index % 2 === 0 ? 'action.hover' : 'transparent',
          cursor: canExecute ? 'pointer' : 'default',
          '&:hover': canExecute ? undefined : { bgcolor: index % 2 === 0 ? 'action.hover' : 'transparent' },
        }}
      >
        <ListItemText
          primary={cl.vorlage_name}
          primaryTypographyProps={{ variant: 'body2' }}
        />
        <Chip
          label={label}
          color={color}
          size="small"
          variant="outlined"
          sx={{ ml: 1, pointerEvents: 'none' }}
        />
        {canExecute && <PlayArrow fontSize="small" color="action" sx={{ ml: 1, opacity: 0.5 }} />}
      </ListItemButton>
    );
  };

  const renderSection = (
    title: string,
    icon: React.ReactNode,
    items: ChecklistOverviewItem[],
    type: 'fahrzeug' | 'ausruestung',
  ) => {
    if (items.length === 0) return null;
    return (
      <Box sx={{ mb: 3 }}>
        <Typography variant="h6" sx={{ mb: 1.5, display: 'flex', alignItems: 'center', gap: 1 }}>
          {icon} {title}
        </Typography>
        {items.map((item) => {
          const totalDue = item.checklists.length;
          const hasOverdue = item.checklists.some((cl) => getDueColor(cl.next_due, cl.intervall) === 'error');
          const badgeColor = hasOverdue ? 'error' : item.checklists.some((cl) => getDueColor(cl.next_due, cl.intervall) === 'warning') ? 'warning' : 'default';
          return (
            <Accordion key={item.id} variant="outlined" disableGutters>
              <AccordionSummary expandIcon={<ExpandMore />}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, width: '100%' }}>
                  <Typography variant="subtitle1">{item.name}</Typography>
                  <Badge
                    badgeContent={totalDue}
                    color={badgeColor as any}
                    sx={{ ml: 'auto', mr: 2 }}
                  />
                </Box>
              </AccordionSummary>
              <AccordionDetails sx={{ p: 0 }}>
                <List dense disablePadding>
                  {item.checklists.map((cl, idx) => renderChecklistRow(cl, item.id, type, idx))}
                </List>
              </AccordionDetails>
            </Accordion>
          );
        })}
      </Box>
    );
  };

  return (
    <Box>
      {renderSection('Fahrzeuge', <DirectionsCar color="action" />, vehicles, 'fahrzeug')}
      {renderSection('Ausrüstung', <BuildCircle color="action" />, equipment, 'ausruestung')}
    </Box>
  );
}

// ══════════════════════════════════════════════════════════════════════════════
// Vorlagen Tab
// ══════════════════════════════════════════════════════════════════════════════

interface VorlagenTabProps {
  vorlagen: ChecklistVorlage[];
  loading: boolean;
  fahrzeugTypen: FahrzeugTyp[];
  queryClient: ReturnType<typeof useQueryClient>;
  showSuccess: (msg: string) => void;
  showError: (msg: string) => void;
}

function VorlagenTab({ vorlagen, loading, fahrzeugTypen, queryClient, showSuccess, showError }: VorlagenTabProps) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingVorlage, setEditingVorlage] = useState<ChecklistVorlage | null>(null);
  const [expandedVorlageId, setExpandedVorlageId] = useState<number | null>(null);

  // Assignment form state
  const [assignmentType, setAssignmentType] = useState<AssignmentType>('global');

  const emptyForm: CreateVorlagePayload = {
    name: '', fahrzeug_typ_ids: [], fahrzeug_ids: [],
    ausruestung_typ_ids: [], ausruestung_ids: [],
    intervall: undefined, intervall_tage: undefined, beschreibung: '', aktiv: true,
  };
  const [form, setForm] = useState<CreateVorlagePayload>(emptyForm);

  // Fetch vehicle / equipment lists for the assignment pickers
  const { data: vehiclesList = [] } = useQuery({
    queryKey: ['vehicles', 'list'],
    queryFn: () => vehiclesApi.getAll(),
    enabled: dialogOpen && assignmentType === 'fahrzeug',
  });
  const { data: equipmentList = [] } = useQuery({
    queryKey: ['equipment', 'list'],
    queryFn: () => equipmentApi.getAll(),
    enabled: dialogOpen && assignmentType === 'ausruestung',
  });
  const { data: ausruestungTypen = [] } = useQuery({
    queryKey: ['ausruestung-typen'],
    queryFn: ausruestungTypenApi.getAll,
    enabled: dialogOpen && assignmentType === 'ausruestung_typ',
  });

  const createMutation = useMutation({
    mutationFn: (data: CreateVorlagePayload) => checklistenApi.createVorlage(data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['checklisten-vorlagen'] }); setDialogOpen(false); showSuccess('Vorlage erstellt'); },
    onError: () => showError('Fehler beim Erstellen der Vorlage'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: UpdateVorlagePayload }) => checklistenApi.updateVorlage(id, data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['checklisten-vorlagen'] }); setDialogOpen(false); showSuccess('Vorlage aktualisiert'); },
    onError: () => showError('Fehler beim Aktualisieren der Vorlage'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => checklistenApi.deleteVorlage(id),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['checklisten-vorlagen'] }); showSuccess('Vorlage gelöscht'); },
    onError: () => showError('Fehler beim Löschen der Vorlage'),
  });

  const openCreate = () => {
    setEditingVorlage(null);
    setForm(emptyForm);
    setAssignmentType('global');
    setDialogOpen(true);
  };
  const openEdit = (v: ChecklistVorlage) => {
    setEditingVorlage(v);
    setAssignmentType(getAssignmentType(v));
    setForm({
      name: v.name,
      fahrzeug_typ_ids: v.fahrzeug_typ_ids ?? [],
      fahrzeug_ids: v.fahrzeug_ids ?? [],
      ausruestung_typ_ids: v.ausruestung_typ_ids ?? [],
      ausruestung_ids: v.ausruestung_ids ?? [],
      intervall: v.intervall,
      intervall_tage: v.intervall_tage,
      beschreibung: v.beschreibung ?? '',
      aktiv: v.aktiv,
    });
    setDialogOpen(true);
  };

  const buildPayload = (): CreateVorlagePayload => {
    const base: CreateVorlagePayload = {
      name: form.name,
      intervall: form.intervall,
      intervall_tage: form.intervall_tage,
      beschreibung: form.beschreibung,
      aktiv: form.aktiv,
    };
    switch (assignmentType) {
      case 'fahrzeug_typ': return { ...base, fahrzeug_typ_ids: form.fahrzeug_typ_ids };
      case 'fahrzeug': return { ...base, fahrzeug_ids: form.fahrzeug_ids };
      case 'ausruestung_typ': return { ...base, ausruestung_typ_ids: form.ausruestung_typ_ids };
      case 'ausruestung': return { ...base, ausruestung_ids: form.ausruestung_ids };
      default: return base;
    }
  };

  const handleSubmit = () => {
    if (!form.name.trim()) return;
    const payload = buildPayload();
    if (editingVorlage) {
      updateMutation.mutate({ id: editingVorlage.id, data: payload });
    } else {
      createMutation.mutate(payload);
    }
  };

  const handleAssignmentTypeChange = (newType: AssignmentType) => {
    setAssignmentType(newType);
    setForm((f) => ({
      ...f,
      fahrzeug_typ_ids: [],
      fahrzeug_ids: [],
      ausruestung_typ_ids: [],
      ausruestung_ids: [],
    }));
  };

  const isSaving = createMutation.isPending || updateMutation.isPending;

  if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2 }}>
        <Button variant="contained" startIcon={<AddIcon />} onClick={openCreate}>Neue Vorlage</Button>
      </Box>

      <TableContainer component={Paper}>
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Zuordnung</TableCell>
              <TableCell>Intervall</TableCell>
              <TableCell>Aktiv</TableCell>
              <TableCell align="right">Aktionen</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {vorlagen.length === 0 ? (
              <TableRow><TableCell colSpan={5} align="center">Keine Vorlagen vorhanden</TableCell></TableRow>
            ) : (
              vorlagen.map((v) => (
                <React.Fragment key={v.id}>
                  <TableRow hover sx={{ cursor: 'pointer' }} onClick={() => setExpandedVorlageId(expandedVorlageId === v.id ? null : v.id)}>
                    <TableCell>{v.name}</TableCell>
                    <TableCell>{getAssignmentLabel(v)}</TableCell>
                    <TableCell>
                      {v.intervall ? INTERVALL_LABELS[v.intervall] || v.intervall : '–'}
                      {v.intervall === 'custom' && v.intervall_tage ? ` (${v.intervall_tage} Tage)` : ''}
                    </TableCell>
                    <TableCell>
                      <Chip label={v.aktiv ? 'Aktiv' : 'Inaktiv'} color={v.aktiv ? 'success' : 'default'} size="small" />
                    </TableCell>
                    <TableCell align="right">
                      <IconButton size="small" onClick={(e) => { e.stopPropagation(); openEdit(v); }}><EditIcon fontSize="small" /></IconButton>
                      <IconButton size="small" color="error" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(v.id); }}><DeleteIcon fontSize="small" /></IconButton>
                    </TableCell>
                  </TableRow>
                  {expandedVorlageId === v.id && (
                    <TableRow>
                      <TableCell colSpan={5} sx={{ p: 2, bgcolor: 'action.hover' }}>
                        <VorlageItemsSection vorlageId={v.id} queryClient={queryClient} showSuccess={showSuccess} showError={showError} />
                      </TableCell>
                    </TableRow>
                  )}
                </React.Fragment>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Create/Edit Dialog */}
      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{editingVorlage ? 'Vorlage bearbeiten' : 'Neue Vorlage'}</DialogTitle>
        <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
          <TextField label="Name *" fullWidth value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} />

          {/* Assignment type */}
          <FormControl>
            <FormLabel>Zuordnung</FormLabel>
            <RadioGroup
              row
              value={assignmentType}
              onChange={(e) => handleAssignmentTypeChange(e.target.value as AssignmentType)}
            >
              <FormControlLabel value="global" control={<Radio size="small" />} label="Global" />
              <FormControlLabel value="fahrzeug_typ" control={<Radio size="small" />} label="Fahrzeugtyp" />
              <FormControlLabel value="fahrzeug" control={<Radio size="small" />} label="Fahrzeug" />
              <FormControlLabel value="ausruestung_typ" control={<Radio size="small" />} label="Ausrüstungstyp" />
              <FormControlLabel value="ausruestung" control={<Radio size="small" />} label="Ausrüstung" />
            </RadioGroup>
          </FormControl>

          {/* Assignment picker based on type */}
          {assignmentType === 'fahrzeug_typ' && (
            <Autocomplete
              multiple
              options={fahrzeugTypen}
              getOptionLabel={(t) => t.name}
              value={fahrzeugTypen.filter((t) => form.fahrzeug_typ_ids?.includes(t.id))}
              onChange={(_e, vals) => setForm((f) => ({ ...f, fahrzeug_typ_ids: vals.map((v) => v.id) }))}
              isOptionEqualToValue={(a, b) => a.id === b.id}
              renderInput={(params) => <TextField {...params} label="Fahrzeugtypen" />}
            />
          )}
          {assignmentType === 'fahrzeug' && (
            <Autocomplete
              multiple
              options={vehiclesList}
              getOptionLabel={(v) => v.bezeichnung ?? v.kurzname ?? String(v.id)}
              value={vehiclesList.filter((v) => form.fahrzeug_ids?.includes(v.id))}
              onChange={(_e, vals) => setForm((f) => ({ ...f, fahrzeug_ids: vals.map((v) => v.id) }))}
              isOptionEqualToValue={(a, b) => a.id === b.id}
              renderInput={(params) => <TextField {...params} label="Fahrzeuge" />}
            />
          )}
          {assignmentType === 'ausruestung_typ' && (
            <Autocomplete
              multiple
              options={ausruestungTypen}
              getOptionLabel={(t: AusruestungTyp) => t.name}
              value={ausruestungTypen.filter((t: AusruestungTyp) => form.ausruestung_typ_ids?.includes(t.id))}
              onChange={(_e, vals: AusruestungTyp[]) => setForm((f) => ({ ...f, ausruestung_typ_ids: vals.map((v) => v.id) }))}
              isOptionEqualToValue={(a: AusruestungTyp, b: AusruestungTyp) => a.id === b.id}
              renderInput={(params) => <TextField {...params} label="Ausrüstungstypen" />}
            />
          )}
          {assignmentType === 'ausruestung' && (
            <Autocomplete
              multiple
              options={equipmentList}
              getOptionLabel={(eq) => eq.bezeichnung ?? String(eq.id)}
              value={equipmentList.filter((eq) => form.ausruestung_ids?.includes(eq.id))}
              onChange={(_e, vals) => setForm((f) => ({ ...f, ausruestung_ids: vals.map((v) => v.id) }))}
              isOptionEqualToValue={(a, b) => a.id === b.id}
              renderInput={(params) => <TextField {...params} label="Ausrüstung" />}
            />
          )}

          <FormControl fullWidth>
            <InputLabel>Intervall</InputLabel>
            <Select label="Intervall" value={form.intervall ?? ''} onChange={(e) => setForm((f) => ({ ...f, intervall: (e.target.value || undefined) as CreateVorlagePayload['intervall'] }))}>
              <MenuItem value="">Kein Intervall</MenuItem>
              <MenuItem value="weekly">Wöchentlich</MenuItem>
              <MenuItem value="monthly">Monatlich</MenuItem>
              <MenuItem value="quarterly">Quartalsweise (alle 3 Monate)</MenuItem>
              <MenuItem value="halfyearly">Halbjährlich (alle 6 Monate)</MenuItem>
              <MenuItem value="yearly">Jährlich</MenuItem>
              <MenuItem value="custom">Benutzerdefiniert (Tage)</MenuItem>
            </Select>
          </FormControl>
          {form.intervall === 'custom' && (
            <TextField label="Intervall (Tage)" type="number" fullWidth value={form.intervall_tage ?? ''} onChange={(e) => setForm((f) => ({ ...f, intervall_tage: e.target.value ? Number(e.target.value) : undefined }))} inputProps={{ min: 1 }} />
          )}
          <TextField label="Beschreibung" fullWidth multiline rows={2} value={form.beschreibung ?? ''} onChange={(e) => setForm((f) => ({ ...f, beschreibung: e.target.value }))} />
          <FormControlLabel control={<Switch checked={form.aktiv !== false} onChange={(e) => setForm((f) => ({ ...f, aktiv: e.target.checked }))} />} label="Aktiv" />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Abbrechen</Button>
          <Button variant="contained" onClick={handleSubmit} disabled={isSaving || !form.name.trim()}>
            {isSaving ? <CircularProgress size={20} /> : 'Speichern'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// ── Vorlage Items Sub-section ──

function VorlageItemsSection({ vorlageId, queryClient, showSuccess, showError }: { vorlageId: number; queryClient: ReturnType<typeof useQueryClient>; showSuccess: (msg: string) => void; showError: (msg: string) => void }) {
  const { data: items = [], isLoading } = useQuery({
    queryKey: ['checklisten-vorlage-items', vorlageId],
    queryFn: () => checklistenApi.getVorlageItems(vorlageId),
  });

  const [newItem, setNewItem] = useState<CreateVorlageItemPayload>({ bezeichnung: '', pflicht: false, sort_order: 0 });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editForm, setEditForm] = useState<{ bezeichnung: string; pflicht: boolean }>({ bezeichnung: '', pflicht: false });
  const [addingSubitemForId, setAddingSubitemForId] = useState<number | null>(null);
  const [newSubitem, setNewSubitem] = useState<{ bezeichnung: string; pflicht: boolean }>({ bezeichnung: '', pflicht: false });

  const addMutation = useMutation({
    mutationFn: (data: CreateVorlageItemPayload) => checklistenApi.addVorlageItem(vorlageId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['checklisten-vorlage-items', vorlageId] });
      setNewItem({ bezeichnung: '', pflicht: false, sort_order: 0 });
      setAddingSubitemForId(null);
      setNewSubitem({ bezeichnung: '', pflicht: false });
      showSuccess('Item hinzugefügt');
    },
    onError: () => showError('Fehler beim Hinzufügen'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: { bezeichnung: string; pflicht: boolean } }) => checklistenApi.updateVorlageItem(id, data),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['checklisten-vorlage-items', vorlageId] }); setEditingId(null); showSuccess('Item aktualisiert'); },
    onError: () => showError('Fehler beim Aktualisieren'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => checklistenApi.deleteVorlageItem(id),
    onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['checklisten-vorlage-items', vorlageId] }); showSuccess('Item entfernt'); },
    onError: () => showError('Fehler beim Entfernen'),
  });

  const startEdit = (item: ChecklistVorlageItem) => {
    setEditingId(item.id);
    setEditForm({ bezeichnung: item.bezeichnung, pflicht: item.pflicht });
  };

  const topLevelItems = items.filter((i) => !i.parent_item_id);
  const getSubitems = (parentId: number) => items.filter((i) => i.parent_item_id === parentId);

  const renderItemRow = (item: ChecklistVorlageItem, isSubitem: boolean) => {
    const subitems = isSubitem ? [] : getSubitems(item.id);
    return (
      <Box key={item.id} sx={{ mb: 0.5 }}>
        {editingId === item.id ? (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, pl: isSubitem ? 4 : 0 }}>
            <TextField
              size="small"
              value={editForm.bezeichnung}
              onChange={(e) => setEditForm((f) => ({ ...f, bezeichnung: e.target.value }))}
              sx={{ flexGrow: 1 }}
              autoFocus
            />
            <FormControlLabel
              control={<Switch size="small" checked={editForm.pflicht} onChange={(e) => setEditForm((f) => ({ ...f, pflicht: e.target.checked }))} />}
              label="Pflicht"
            />
            <Button
              size="small"
              variant="contained"
              disabled={!editForm.bezeichnung.trim() || updateMutation.isPending}
              onClick={() => updateMutation.mutate({ id: item.id, data: editForm })}
            >
              Speichern
            </Button>
            <Button size="small" onClick={() => setEditingId(null)}>Abbrechen</Button>
          </Box>
        ) : (
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, pl: isSubitem ? 4 : 0 }}>
            <Typography variant="body2" sx={{ flexGrow: 1 }}>
              {item.bezeichnung} {item.pflicht && <Chip label="Pflicht" size="small" color="warning" sx={{ ml: 0.5 }} />}
            </Typography>
            {!isSubitem && (
              <Tooltip title="Unteritem hinzufügen">
                <IconButton size="small" onClick={() => { setAddingSubitemForId(item.id); setNewSubitem({ bezeichnung: '', pflicht: false }); }}>
                  <AddIcon fontSize="small" />
                </IconButton>
              </Tooltip>
            )}
            <IconButton size="small" onClick={() => startEdit(item)}><EditIcon fontSize="small" /></IconButton>
            <IconButton size="small" color="error" onClick={() => deleteMutation.mutate(item.id)}><DeleteIcon fontSize="small" /></IconButton>
          </Box>
        )}
        {subitems.map((sub) => renderItemRow(sub, true))}
        {addingSubitemForId === item.id && (
          <Box sx={{ display: 'flex', gap: 1, mt: 0.5, pl: 4, alignItems: 'center' }}>
            <TextField
              size="small"
              placeholder="Unteritem..."
              value={newSubitem.bezeichnung}
              onChange={(e) => setNewSubitem((n) => ({ ...n, bezeichnung: e.target.value }))}
              sx={{ flexGrow: 1 }}
              autoFocus
            />
            <FormControlLabel
              control={<Switch size="small" checked={newSubitem.pflicht} onChange={(e) => setNewSubitem((n) => ({ ...n, pflicht: e.target.checked }))} />}
              label="Pflicht"
            />
            <Button
              size="small"
              variant="outlined"
              disabled={!newSubitem.bezeichnung.trim() || addMutation.isPending}
              onClick={() => addMutation.mutate({ ...newSubitem, parent_item_id: item.id })}
            >
              Hinzufügen
            </Button>
            <Button size="small" onClick={() => setAddingSubitemForId(null)}>Abbrechen</Button>
          </Box>
        )}
      </Box>
    );
  };

  if (isLoading) return <CircularProgress size={20} />;

  return (
    <Box>
      <Typography variant="subtitle2" sx={{ mb: 1 }}>Checklisten-Items</Typography>
      {topLevelItems.map((item) => renderItemRow(item, false))}
      <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center' }}>
        <TextField size="small" placeholder="Neues Item..." value={newItem.bezeichnung} onChange={(e) => setNewItem((n) => ({ ...n, bezeichnung: e.target.value }))} sx={{ flexGrow: 1 }} />
        <FormControlLabel control={<Switch size="small" checked={newItem.pflicht} onChange={(e) => setNewItem((n) => ({ ...n, pflicht: e.target.checked }))} />} label="Pflicht" />
        <Button size="small" variant="outlined" disabled={!newItem.bezeichnung.trim() || addMutation.isPending} onClick={() => addMutation.mutate(newItem)}>
          Hinzufügen
        </Button>
      </Box>
    </Box>
  );
}

// ══════════════════════════════════════════════════════════════════════════════
// Historie Tab
// ══════════════════════════════════════════════════════════════════════════════

interface HistorieTabProps {
  executions: ChecklistAusfuehrung[];
  loading: boolean;
  navigate: ReturnType<typeof useNavigate>;
}

function HistorieTab({ executions, loading, navigate }: HistorieTabProps) {
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [targetFilter, setTargetFilter] = useState<string>('');

  const filtered = executions.filter((e) => {
    if (statusFilter && e.status !== statusFilter) return false;
    const targetName = e.fahrzeug_name || e.ausruestung_name || '';
    if (targetFilter && targetName !== targetFilter) return false;
    return true;
  });

  const uniqueTargets = [...new Set(
    executions.map((e) => e.fahrzeug_name || e.ausruestung_name).filter(Boolean)
  )] as string[];

  if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress /></Box>;

  const columns: Column<ChecklistAusfuehrung>[] = [
    { key: 'fahrzeug_name', label: 'Fahrzeug / Ausrüstung', render: (e) => e.fahrzeug_name || e.ausruestung_name || '–' },
    { key: 'vorlage_name', label: 'Vorlage', render: (e) => e.vorlage_name ?? '–' },
    { key: 'ausgefuehrt_am', label: 'Datum', render: (e) => formatDate(e.ausgefuehrt_am ?? e.created_at) },
    { key: 'status', label: 'Status', render: (e) => (
      <Chip label={CHECKLIST_STATUS_LABELS[e.status]} color={CHECKLIST_STATUS_COLORS[e.status]} size="small" />
    )},
    { key: 'ausgefuehrt_von_name', label: 'Ausgeführt von', render: (e) => e.ausgefuehrt_von_name ?? '–' },
    { key: 'freigegeben_von_name', label: 'Freigegeben von', render: (e) => e.freigegeben_von_name ?? '–' },
  ];

  return (
    <Box>
      <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
        <FormControl size="small" sx={{ minWidth: 160 }}>
          <InputLabel>Status</InputLabel>
          <Select label="Status" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
            <MenuItem value="">Alle</MenuItem>
            {Object.entries(CHECKLIST_STATUS_LABELS).map(([key, label]) => (
              <MenuItem key={key} value={key}>{label}</MenuItem>
            ))}
          </Select>
        </FormControl>
        <FormControl size="small" sx={{ minWidth: 200 }}>
          <InputLabel>Fahrzeug / Ausrüstung</InputLabel>
          <Select label="Fahrzeug / Ausrüstung" value={targetFilter} onChange={(e) => setTargetFilter(e.target.value)}>
            <MenuItem value="">Alle</MenuItem>
            {uniqueTargets.map((v) => <MenuItem key={v} value={v}>{v}</MenuItem>)}
          </Select>
        </FormControl>
      </Box>

      <DataTable
        columns={columns}
        data={filtered}
        rowKey={(e) => e.id}
        onRowClick={(e) => navigate(`/checklisten/ausfuehrung/${e.id}`)}
        emptyMessage="Keine Einträge"
        searchEnabled={false}
      />
    </Box>
  );
}
