import React from 'react';
import {
  Alert,
  AlertTitle,
  Box,
  Typography,
} from '@mui/material';
import HandymanIcon from '@mui/icons-material/Handyman';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { equipmentApi } from '../../services/equipment';
import { useCountUp } from '../../hooks/useCountUp';
import type { EquipmentStats } from '../../types/equipment.types';
import { WidgetCard } from '../templates/WidgetCard';
import { StatSkeleton } from '../templates/SkeletonPresets';

interface EquipmentDashboardCardProps {
  hideWhenEmpty?: boolean;
}

const EquipmentDashboardCard: React.FC<EquipmentDashboardCardProps> = ({
  hideWhenEmpty = false,
}) => {
  const navigate = useNavigate();
  const { data: stats, isLoading, isError } = useQuery<EquipmentStats>({
    queryKey: ['equipment-stats'],
    queryFn: () => equipmentApi.getStats(),
  });

  const animatedReady = useCountUp(stats?.einsatzbereit ?? 0);
  const animatedTotal = useCountUp(stats?.total ?? 0);

  const hasCritical = stats
    ? stats.wichtigNichtBereit > 0 || stats.inspectionsOverdue > 0 || stats.beschaedigt > 0
    : false;
  const hasWarning = stats
    ? stats.inspectionsDue > 0 || stats.inWartung > 0 || stats.ausserDienst > 0
    : false;
  const allGood = stats ? stats.einsatzbereit === stats.total && !hasCritical && !hasWarning : false;

  if (!isLoading && !isError && stats && hideWhenEmpty && allGood) return null;

  return (
    <WidgetCard
      title="Ausrüstung"
      icon={<HandymanIcon />}
      isLoading={isLoading}
      isError={isError}
      errorMessage="Ausrüstungsstatus konnte nicht geladen werden."
      skeleton={<StatSkeleton />}
      onClick={() => navigate('/ausruestung')}
    >
      <Typography variant="h4" fontWeight={700} color={allGood ? 'success.main' : 'text.primary'}>
        {animatedReady}/{animatedTotal}
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
        einsatzbereit
      </Typography>

      {(hasCritical || hasWarning) && (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, mt: 1 }}>
          {hasCritical && stats && (
            <Alert severity="error" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Kritisch</AlertTitle>
              {stats.wichtigNichtBereit > 0 && (
                <Typography variant="body2">{stats.wichtigNichtBereit} wichtige Teile nicht einsatzbereit</Typography>
              )}
              {stats.inspectionsOverdue > 0 && (
                <Typography variant="body2">{stats.inspectionsOverdue} Prüfung{stats.inspectionsOverdue !== 1 ? 'en' : ''} überfällig</Typography>
              )}
              {stats.beschaedigt > 0 && (
                <Typography variant="body2">{stats.beschaedigt} beschädigt</Typography>
              )}
            </Alert>
          )}
          {hasWarning && stats && (
            <Alert severity="warning" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Achtung</AlertTitle>
              {stats.inspectionsDue > 0 && (
                <Typography variant="body2">{stats.inspectionsDue} Prüfung{stats.inspectionsDue !== 1 ? 'en' : ''} bald fällig</Typography>
              )}
              {stats.inWartung > 0 && (
                <Typography variant="body2">{stats.inWartung} in Wartung</Typography>
              )}
              {stats.ausserDienst > 0 && (
                <Typography variant="body2">{stats.ausserDienst} außer Dienst</Typography>
              )}
            </Alert>
          )}
        </Box>
      )}

      {allGood && (
        <Typography variant="body2" color="success.main">
          Alle Ausrüstung einsatzbereit
        </Typography>
      )}
    </WidgetCard>
  );
};

export default EquipmentDashboardCard;
