import { Box, Chip } from '@mui/material';
import { Build } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { ausruestungsanfrageApi } from '../../services/ausruestungsanfrage';
import type { AusruestungWidgetOverview } from '../../types/ausruestungsanfrage.types';
import { WidgetCard } from '../templates/WidgetCard';
import { ChipListSkeleton } from '../templates/SkeletonPresets';

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

  const { data: overview, isLoading, isError } = useQuery<AusruestungWidgetOverview>({
    queryKey: ['ausruestungsanfrage-widget-overview'],
    queryFn: () => ausruestungsanfrageApi.getWidgetOverview(),
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const hasAny = (overview?.total_count ?? 0) > 0;

  return (
    <WidgetCard
      title="Interne Bestellungen"
      icon={<Build fontSize="small" />}
      isLoading={isLoading}
      skeleton={<ChipListSkeleton />}
      isError={isError || (!isLoading && !overview)}
      errorMessage="Daten konnten nicht geladen werden."
      isEmpty={!isLoading && !isError && !!overview && !hasAny}
      emptyMessage="Keine Anfragen vorhanden."
      onClick={() => navigate('/ausruestungsanfrage')}
    >
      <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
        {overview && overview.unhandled_count > 0 && (
          <Chip label={`${overview.unhandled_count} Neu`} size="small" color="error" variant="outlined" />
        )}
        {overview && overview.pending_count > 0 && (
          <Chip label={`${overview.pending_count} Offen`} size="small" color="warning" variant="outlined" />
        )}
        {overview && overview.approved_count > 0 && (
          <Chip label={`${overview.approved_count} Genehmigt`} size="small" color="info" variant="outlined" />
        )}
      </Box>
    </WidgetCard>
  );
}

export default AusruestungsanfrageWidget;
