import { Typography, Box, Chip } from '@mui/material';
import { AssignmentTurnedIn, Warning } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { checklistenApi } from '../../services/checklisten';
import { WidgetCard } from '../templates/WidgetCard';
import { ChipListSkeleton } from '../templates/SkeletonPresets';

function ChecklistWidget() {
  const navigate = useNavigate();

  const { data: overdue, isLoading, isError } = useQuery({
    queryKey: ['checklist-overdue'],
    queryFn: checklistenApi.getOverdue,
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const overdueItems = overdue ?? [];

  const titleAction = !isLoading && !isError && overdueItems.length > 0 ? (
    <Chip icon={<Warning />} label={overdueItems.length} color="error" size="small" />
  ) : undefined;

  return (
    <WidgetCard
      title="Checklisten"
      icon={<AssignmentTurnedIn fontSize="small" />}
      action={titleAction}
      isLoading={isLoading}
      skeleton={<ChipListSkeleton />}
      isError={isError}
      errorMessage="Checklisten konnten nicht geladen werden."
      isEmpty={!isLoading && !isError && overdueItems.length === 0}
      emptyMessage="Alle Checklisten aktuell"
      onClick={() => navigate('/checklisten')}
    >
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
        {overdueItems.slice(0, 5).map((item) => {
          const days = Math.ceil((Date.now() - new Date(item.naechste_faellig_am).getTime()) / 86400000);
          const targetName = item.fahrzeug_name || item.ausruestung_name || '–';
          return (
            <Box key={`${item.fahrzeug_id || item.ausruestung_id}-${item.vorlage_id}`} sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="body2" noWrap sx={{ maxWidth: '60%' }}>
                {targetName}
              </Typography>
              <Chip
                label={`${item.vorlage_name} \u2013 ${days > 0 ? `${days}d` : 'heute'}`}
                color={days > 7 ? 'error' : days > 0 ? 'warning' : 'info'}
                size="small"
                variant="outlined"
              />
            </Box>
          );
        })}
        {overdueItems.length > 5 && (
          <Typography variant="caption" color="text.secondary">
            + {overdueItems.length - 5} weitere
          </Typography>
        )}
      </Box>
    </WidgetCard>
  );
}

export default ChecklistWidget;
