import { Box, Chip } from '@mui/material';
import { LocalShipping } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { bestellungApi } from '../../services/bestellung';
import { BESTELLUNG_STATUS_LABELS, BESTELLUNG_STATUS_COLORS } from '../../types/bestellung.types';
import type { BestellungStatus } from '../../types/bestellung.types';
import { WidgetCard } from '../templates/WidgetCard';
import { ChipListSkeleton } from '../templates/SkeletonPresets';

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

  const { data: orders, isLoading, isError } = useQuery({
    queryKey: ['bestellungen-widget'],
    queryFn: () => bestellungApi.getOrders(),
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const openOrders = (orders ?? []).filter(
    (o) => !['abgeschlossen'].includes(o.status)
  );

  // Group open orders by status, keep only non-zero counts
  const statusCounts = (Object.keys(BESTELLUNG_STATUS_LABELS) as BestellungStatus[])
    .filter((s) => s !== 'abgeschlossen')
    .map((s) => ({ status: s, count: openOrders.filter((o) => o.status === s).length }))
    .filter((s) => s.count > 0);

  return (
    <WidgetCard
      title="Bestellungen"
      icon={<LocalShipping fontSize="small" />}
      isLoading={isLoading}
      skeleton={<ChipListSkeleton />}
      isError={isError}
      errorMessage="Bestellungen konnten nicht geladen werden."
      isEmpty={!isLoading && !isError && statusCounts.length === 0}
      emptyMessage="Keine offenen Bestellungen"
      onClick={() => navigate('/bestellungen')}
    >
      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
        {statusCounts.map(({ status, count }) => (
          <Chip
            key={status}
            label={`${count} ${BESTELLUNG_STATUS_LABELS[status]}`}
            color={BESTELLUNG_STATUS_COLORS[status]}
            size="small"
            variant="outlined"
          />
        ))}
      </Box>
    </WidgetCard>
  );
}

export default BestellungenWidget;
