import { Box, Chip } from '@mui/material';
import { BugReport } from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { issuesApi } from '../../services/issues';
import { WidgetCard } from '../templates/WidgetCard';
import { ChipListSkeleton } from '../templates/SkeletonPresets';

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

  const { data = [], isLoading, isError } = useQuery({
    queryKey: ['issues-widget-summary'],
    queryFn: issuesApi.getWidgetSummary,
    refetchInterval: 5 * 60 * 1000,
    retry: 1,
  });

  const visibleCounts = data.filter((s) => s.count > 0);

  return (
    <WidgetCard
      title="Issues"
      icon={<BugReport fontSize="small" />}
      isLoading={isLoading}
      skeleton={<ChipListSkeleton />}
      isError={isError}
      errorMessage="Issues konnten nicht geladen werden."
      isEmpty={!isLoading && !isError && visibleCounts.length === 0}
      emptyMessage="Keine offenen Issues"
      onClick={() => navigate('/issues')}
    >
      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
        {visibleCounts.map((s) => (
          <Chip
            key={s.schluessel}
            label={`${s.count} ${s.bezeichnung}`}
            color={s.farbe as any}
            size="small"
          />
        ))}
      </Box>
    </WidgetCard>
  );
}

export default IssueOverviewWidget;
