import { useState, useEffect } from 'react';
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  Divider,
  Paper,
  Radio,
  RadioGroup,
  FormControlLabel,
  TextField,
  Typography,
} from '@mui/material';
import { ArrowBack, CheckCircle, Cancel, RemoveCircle } from '@mui/icons-material';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { usePermissionContext } from '../contexts/PermissionContext';
import { useNotification } from '../contexts/NotificationContext';
import { checklistenApi } from '../services/checklisten';
import { CHECKLIST_STATUS_LABELS, CHECKLIST_STATUS_COLORS } from '../types/checklist.types';
import { StatusChip } from '../components/templates';
import type { ChecklistAusfuehrungItem } from '../types/checklist.types';

// ── Helpers ──

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

const ERGEBNIS_ICONS: Record<string, JSX.Element> = {
  ok: <CheckCircle fontSize="small" color="success" />,
  nok: <Cancel fontSize="small" color="error" />,
  na: <RemoveCircle fontSize="small" color="disabled" />,
};

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

export default function ChecklistAusfuehrung() {
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { hasPermission } = usePermissionContext();
  const { showSuccess, showError } = useNotification();

  const isNew = id === 'new';
  const canApprove = hasPermission('checklisten:approve');

  // ── Start new execution ──
  const [startingExecution, setStartingExecution] = useState(false);

  useEffect(() => {
    if (!isNew || startingExecution) return;
    const fahrzeugId = searchParams.get('fahrzeug');
    const ausruestungId = searchParams.get('ausruestung');
    const vorlageId = searchParams.get('vorlage');
    if (!vorlageId || (!fahrzeugId && !ausruestungId)) {
      showError('Vorlage und entweder Fahrzeug oder Ausrüstung sind erforderlich');
      navigate('/checklisten');
      return;
    }
    setStartingExecution(true);
    checklistenApi.startExecution(Number(vorlageId), { fahrzeugId: fahrzeugId ?? undefined, ausruestungId: ausruestungId ?? undefined })
      .then((exec) => navigate(`/checklisten/ausfuehrung/${exec.id}`, { replace: true }))
      .catch(() => { showError('Checkliste konnte nicht gestartet werden'); navigate('/checklisten'); });
  }, [isNew, searchParams, navigate, showError, startingExecution]);

  // ── Fetch existing execution ──
  const { data: execution, isLoading, isError } = useQuery({
    queryKey: ['checklisten-ausfuehrung', id],
    queryFn: () => checklistenApi.getExecution(id!),
    enabled: !isNew && !!id,
  });

  // ── Item state ──
  const [itemResults, setItemResults] = useState<Record<number, { ergebnis: 'ok' | 'nok' | 'na'; kommentar: string }>>({});
  const [notizen, setNotizen] = useState('');

  useEffect(() => {
    if (!execution?.items) return;
    const results: Record<number, { ergebnis: 'ok' | 'nok' | 'na'; kommentar: string }> = {};
    for (const item of execution.items) {
      results[item.id] = { ergebnis: item.ergebnis ?? 'ok', kommentar: item.kommentar ?? '' };
    }
    setItemResults(results);
    setNotizen(execution.notizen ?? '');
  }, [execution]);

  const setItemResult = (itemId: number, ergebnis: 'ok' | 'nok' | 'na') => {
    setItemResults((prev) => ({ ...prev, [itemId]: { ...prev[itemId], ergebnis } }));
  };

  const setItemComment = (itemId: number, kommentar: string) => {
    setItemResults((prev) => ({ ...prev, [itemId]: { ...prev[itemId], kommentar } }));
  };

  // ── Submit ──
  const submitMutation = useMutation({
    mutationFn: () => {
      // Exclude parent items (those that have children) from the submit payload
      const parentIds = new Set(
        (execution?.items ?? [])
          .filter((i) => i.parent_ausfuehrung_item_id != null)
          .map((i) => i.parent_ausfuehrung_item_id!)
      );
      return checklistenApi.submitExecution(id!, {
        items: Object.entries(itemResults)
          .filter(([itemId]) => !parentIds.has(Number(itemId)))
          .map(([itemId, r]) => ({ itemId: Number(itemId), ergebnis: r.ergebnis, kommentar: r.kommentar || undefined })),
        notizen: notizen || undefined,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['checklisten-ausfuehrung', id] });
      queryClient.invalidateQueries({ queryKey: ['checklisten-ausfuehrungen'] });
      queryClient.invalidateQueries({ queryKey: ['checklisten-faellig'] });
      showSuccess('Checkliste abgeschlossen');
    },
    onError: () => showError('Fehler beim Abschließen'),
  });

  // ── Approve ──
  const approveMutation = useMutation({
    mutationFn: () => checklistenApi.approveExecution(id!),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['checklisten-ausfuehrung', id] });
      queryClient.invalidateQueries({ queryKey: ['checklisten-ausfuehrungen'] });
      showSuccess('Checkliste freigegeben');
    },
    onError: () => showError('Fehler bei der Freigabe'),
  });

  // ── Loading states ──
  if (isNew) {
    return (
      <DashboardLayout>
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}><CircularProgress /></Box>
      </DashboardLayout>
    );
  }

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

  if (isError || !execution) {
    return (
      <DashboardLayout>
        <Alert severity="error">Checkliste konnte nicht geladen werden.</Alert>
        <Button startIcon={<ArrowBack />} onClick={() => navigate('/checklisten')} sx={{ mt: 2 }}>Zurück</Button>
      </DashboardLayout>
    );
  }

  const isReadOnly = execution.status === 'abgeschlossen' || execution.status === 'freigegeben';
  const items = execution.items ?? [];
  const vorlageItems = items.filter((i) => i.vorlage_item_id != null);
  const vehicleItems = items.filter((i) => i.fahrzeug_item_id != null);
  const equipmentItems = items.filter((i) => i.ausruestung_item_id != null);

  const renderItemGroup = (groupItems: ChecklistAusfuehrungItem[], title: string) => {
    if (groupItems.length === 0) return null;

    const topLevel = groupItems.filter((i) => !i.parent_ausfuehrung_item_id);
    const getSubitems = (parentId: number) => groupItems.filter((i) => i.parent_ausfuehrung_item_id === parentId);

    const renderSingleItem = (item: ChecklistAusfuehrungItem, isSubitem: boolean) => {
      const result = itemResults[item.id];
      return (
        <Paper key={item.id} variant="outlined" sx={{ p: 2, mb: 1, ml: isSubitem ? 2 : 0 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
            <Typography variant="body1" sx={{ fontWeight: 500, flexGrow: 1 }}>
              {item.bezeichnung}
            </Typography>
            {isReadOnly && result?.ergebnis && ERGEBNIS_ICONS[result.ergebnis]}
          </Box>
          {isReadOnly ? (
            <Box>
              <Chip
                label={result?.ergebnis === 'ok' ? 'OK' : result?.ergebnis === 'nok' ? 'Nicht OK' : 'N/A'}
                color={result?.ergebnis === 'ok' ? 'success' : result?.ergebnis === 'nok' ? 'error' : 'default'}
                size="small"
              />
              {result?.kommentar && (
                <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>{result.kommentar}</Typography>
              )}
            </Box>
          ) : (
            <Box>
              <RadioGroup
                row
                value={result?.ergebnis ?? ''}
                onChange={(e) => setItemResult(item.id, e.target.value as 'ok' | 'nok' | 'na')}
              >
                <FormControlLabel value="ok" control={<Radio size="small" />} label="OK" />
                <FormControlLabel value="nok" control={<Radio size="small" />} label="Nicht OK" />
                <FormControlLabel value="na" control={<Radio size="small" />} label="N/A" />
              </RadioGroup>
              <TextField
                size="small"
                placeholder="Kommentar (optional)"
                fullWidth
                value={result?.kommentar ?? ''}
                onChange={(e) => setItemComment(item.id, e.target.value)}
                sx={{ mt: 0.5 }}
              />
            </Box>
          )}
        </Paper>
      );
    };

    const renderItem = (item: ChecklistAusfuehrungItem) => {
      const subitems = getSubitems(item.id);
      if (subitems.length > 0) {
        return (
          <Box key={item.id} sx={{ mb: 1 }}>
            <Typography variant="subtitle2" sx={{ fontWeight: 600, mt: 1, mb: 0.5 }}>{item.bezeichnung}</Typography>
            {subitems.map((sub) => renderSingleItem(sub, true))}
          </Box>
        );
      }
      return renderSingleItem(item, false);
    };

    return (
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 1 }}>{title}</Typography>
        {topLevel.map((item) => renderItem(item))}
      </Box>
    );
  };

  return (
    <DashboardLayout>
      <Button startIcon={<ArrowBack />} onClick={() => navigate('/checklisten')} sx={{ mb: 2 }} size="small">
        Checklisten
      </Button>

      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
        <Box>
          <Typography variant="h4">
            {execution.vorlage_name ?? 'Checkliste'}
          </Typography>
          <Typography variant="subtitle1" color="text.secondary">
            {execution.fahrzeug_name ?? execution.ausruestung_name ?? '–'} &middot; {formatDate(execution.ausgefuehrt_am ?? execution.created_at)}
          </Typography>
        </Box>
        <StatusChip
          status={execution.status}
          labelMap={CHECKLIST_STATUS_LABELS}
          colorMap={CHECKLIST_STATUS_COLORS}
          size="medium"
        />
      </Box>

      {execution.status === 'unvollstaendig' && (
        <Alert severity="warning" sx={{ mb: 2 }}>
          Diese Checkliste wurde als unvollständig abgeschlossen. Einige Pflicht-Items wurden nicht mit &quot;OK&quot; bewertet.
        </Alert>
      )}

      <Card sx={{ mb: 3 }}>
        <CardContent>
          {renderItemGroup(vorlageItems, 'Vorlage-Items')}
          {vorlageItems.length > 0 && vehicleItems.length > 0 && <Divider sx={{ my: 2 }} />}
          {renderItemGroup(vehicleItems, 'Fahrzeugspezifische Items')}
          {(vorlageItems.length > 0 || vehicleItems.length > 0) && equipmentItems.length > 0 && <Divider sx={{ my: 2 }} />}
          {renderItemGroup(equipmentItems, 'Ausrüstungsspezifische Items')}

          {items.length === 0 && (
            <Typography color="text.secondary">Keine Items in dieser Checkliste.</Typography>
          )}
        </CardContent>
      </Card>

      {/* Notes */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 1 }}>Notizen</Typography>
          {isReadOnly ? (
            <Typography variant="body2" color="text.secondary">{execution.notizen || 'Keine Notizen'}</Typography>
          ) : (
            <TextField
              fullWidth
              multiline
              rows={3}
              placeholder="Zusätzliche Notizen..."
              value={notizen}
              onChange={(e) => setNotizen(e.target.value)}
            />
          )}
        </CardContent>
      </Card>

      {/* Actions */}
      <Box sx={{ display: 'flex', gap: 2 }}>
        {execution.status === 'offen' && (
          <Button
            variant="contained"
            onClick={() => submitMutation.mutate()}
            disabled={submitMutation.isPending}
            startIcon={submitMutation.isPending ? <CircularProgress size={16} /> : undefined}
          >
            Abschließen
          </Button>
        )}

        {canApprove && execution.status === 'abgeschlossen' && (
          <Button
            variant="contained"
            color="success"
            onClick={() => approveMutation.mutate()}
            disabled={approveMutation.isPending}
            startIcon={approveMutation.isPending ? <CircularProgress size={16} /> : undefined}
          >
            Freigeben
          </Button>
        )}
      </Box>

      {/* Metadata */}
      {(execution.ausgefuehrt_von_name || execution.freigegeben_von_name) && (
        <Paper variant="outlined" sx={{ p: 2, mt: 3 }}>
          {execution.ausgefuehrt_von_name && (
            <Typography variant="body2" color="text.secondary">
              Ausgeführt von: {execution.ausgefuehrt_von_name} am {formatDate(execution.ausgefuehrt_am)}
            </Typography>
          )}
          {execution.freigegeben_von_name && (
            <Typography variant="body2" color="text.secondary">
              Freigegeben von: {execution.freigegeben_von_name} am {formatDate(execution.freigegeben_am)}
            </Typography>
          )}
        </Paper>
      )}
    </DashboardLayout>
  );
}
