import React from 'react';
import {
  Alert,
  AlertTitle,
  Box,
  Typography,
} from '@mui/material';
import FireTruckIcon from '@mui/icons-material/FireTruck';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { vehiclesApi } from '../../services/vehicles';
import { equipmentApi } from '../../services/equipment';
import { useCountUp } from '../../hooks/useCountUp';
import type { VehicleStats, InspectionAlert } from '../../types/vehicle.types';
import type { VehicleEquipmentWarning } from '../../types/equipment.types';
import { WidgetCard } from '../templates/WidgetCard';
import { StatSkeleton } from '../templates/SkeletonPresets';

interface VehicleDashboardCardProps {
  hideWhenEmpty?: boolean;
}

const VehicleDashboardCard: React.FC<VehicleDashboardCardProps> = ({
  hideWhenEmpty = false,
}) => {
  const navigate = useNavigate();
  const { data: stats, isLoading: statsLoading, isError: statsError } = useQuery<VehicleStats>({
    queryKey: ['vehicle-stats'],
    queryFn: () => vehiclesApi.getStats(),
  });

  const { data: alerts = [], isLoading: alertsLoading } = useQuery<InspectionAlert[]>({
    queryKey: ['vehicle-alerts'],
    queryFn: () => vehiclesApi.getAlerts(30),
  });

  const { data: equipmentWarnings = [], isLoading: warningsLoading } = useQuery<VehicleEquipmentWarning[]>({
    queryKey: ['vehicle-equipment-warnings'],
    queryFn: () => equipmentApi.getVehicleWarnings(),
  });

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

  const loading = statsLoading || alertsLoading || warningsLoading;

  if (!loading && !statsError && stats) {
    const overdueAlerts = alerts.filter((a) => a.tage < 0);
    const hasConcerns =
      overdueAlerts.length > 0 ||
      stats.ausserDienst > 0 ||
      equipmentWarnings.length > 0;
    const allGood = stats.einsatzbereit === stats.total && !hasConcerns;
    if (hideWhenEmpty && allGood) return null;
  }

  const overdueAlerts = alerts.filter((a) => a.tage < 0);
  const upcomingAlerts = alerts.filter((a) => a.tage >= 0 && a.tage <= 30);
  const hasConcerns =
    overdueAlerts.length > 0 ||
    upcomingAlerts.length > 0 ||
    (stats?.ausserDienst ?? 0) > 0 ||
    equipmentWarnings.length > 0;
  const allGood = stats ? stats.einsatzbereit === stats.total && !hasConcerns : false;

  return (
    <WidgetCard
      title="Fahrzeuge"
      icon={<FireTruckIcon />}
      isLoading={loading}
      isError={statsError}
      errorMessage="Fahrzeugstatus konnte nicht geladen werden."
      skeleton={<StatSkeleton />}
      onClick={() => navigate('/fahrzeuge')}
    >
      <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>

      {hasConcerns && (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, mt: 1 }}>
          {overdueAlerts.length > 0 && (
            <Alert severity="error" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Überfällig</AlertTitle>
              <Typography variant="body2">
                {overdueAlerts.length} Prüfung{overdueAlerts.length !== 1 ? 'en' : ''} überfällig
              </Typography>
            </Alert>
          )}
          {(stats?.ausserDienst ?? 0) > 0 && (
            <Alert severity="error" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Außer Dienst</AlertTitle>
              <Typography variant="body2">
                {stats!.ausserDienst} Fahrzeug{stats!.ausserDienst !== 1 ? 'e' : ''} außer Dienst
              </Typography>
            </Alert>
          )}
          {upcomingAlerts.length > 0 && (
            <Alert severity="warning" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Bald fällig</AlertTitle>
              <Typography variant="body2">
                {upcomingAlerts.length} Prüfung{upcomingAlerts.length !== 1 ? 'en' : ''} bald fällig
              </Typography>
            </Alert>
          )}
          {equipmentWarnings.length > 0 && (
            <Alert severity="warning" variant="outlined" sx={{ py: 0.5 }}>
              <AlertTitle sx={{ fontWeight: 600, mb: 0.5 }}>Ausrüstung nicht verfügbar</AlertTitle>
              <Typography variant="body2">
                {equipmentWarnings.length} Ausrüstungsgegenstand{equipmentWarnings.length !== 1 ? 'stände' : 'stand'} nicht einsatzbereit
              </Typography>
            </Alert>
          )}
        </Box>
      )}

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

export default VehicleDashboardCard;
