/**
 * @ai-summary Main dashboard screen showing vehicle fleet roster with health indicators
 */

import React, { useState } from 'react';
import { Box, Dialog, DialogTitle, DialogContent, IconButton, Skeleton, Typography, useMediaQuery, useTheme } from '@mui/material';
import WarningAmberRoundedIcon from '@mui/icons-material/WarningAmberRounded';
import DirectionsCarRoundedIcon from '@mui/icons-material/DirectionsCarRounded';
import CloseIcon from '@mui/icons-material/Close';
import { VehicleRosterCard } from './VehicleRosterCard';
import { ActionBar } from './ActionBar';
import { useVehicleRoster } from '../hooks/useDashboardData';
import { GlassCard } from '../../../shared-minimal/components/mobile/GlassCard';
import { Button } from '../../../shared-minimal/components/Button';
import { PendingAssociationBanner } from '../../email-ingestion/components/PendingAssociationBanner';
import { PendingAssociationList } from '../../email-ingestion/components/PendingAssociationList';
import { MobileScreen } from '../../../core/store';
import { Vehicle } from '../../vehicles/types/vehicles.types';

interface DashboardScreenProps {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- matches navigation store type signature
  onNavigate?: (screen: MobileScreen, metadata?: Record<string, any>) => void;
  onVehicleClick?: (vehicle: Vehicle) => void;
  onViewMaintenance?: () => void;
  onAddVehicle?: () => void;
}

const RosterSkeleton: React.FC = () => (
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
    {[0, 1, 2, 3].map(i => (
      <GlassCard key={i}>
        <div className="flex items-center gap-3 mb-3">
          <Skeleton variant="circular" width={48} height={48} />
          <div className="flex-1">
            <Skeleton variant="text" width="60%" />
          </div>
          <Skeleton variant="circular" width={12} height={12} />
        </div>
        <div className="mb-3 space-y-1">
          <Skeleton variant="text" width="80%" />
          <Skeleton variant="text" width="80%" />
        </div>
        <Skeleton variant="text" width="30%" />
      </GlassCard>
    ))}
  </div>
);

export const DashboardScreen: React.FC<DashboardScreenProps> = ({
  onNavigate,
  onVehicleClick,
  onAddVehicle,
}) => {
  const theme = useTheme();
  const isSmall = useMediaQuery(theme.breakpoints.down('sm'));
  const [showPendingReceipts, setShowPendingReceipts] = useState(false);
  const { data: roster, vehicles, isLoading, error } = useVehicleRoster();

  const handleAddVehicle = onAddVehicle ?? (() => onNavigate?.('Vehicles'));
  const handleLogFuel = () => onNavigate?.('Log Fuel');
  const handleVehicleClick = (vehicleId: string) => {
    const vehicle = vehicles?.find(v => v.id === vehicleId);
    if (vehicle && onVehicleClick) {
      onVehicleClick(vehicle);
    }
  };

  // Error state
  if (error) {
    return (
      <div className="space-y-4">
        <GlassCard>
          <div className="text-center py-12">
            <Box sx={{ color: 'warning.main', mb: 1.5 }}>
              <WarningAmberRoundedIcon sx={{ fontSize: 48 }} />
            </Box>
            <h2 className="text-lg font-semibold text-slate-800 dark:text-avus mb-2">
              Unable to Load Dashboard
            </h2>
            <p className="text-slate-500 dark:text-titanio mb-4">
              There was an error loading your dashboard data
            </p>
            <Button
              variant="primary"
              size="md"
              onClick={() => window.location.reload()}
            >
              Retry
            </Button>
          </div>
        </GlassCard>
      </div>
    );
  }

  // Loading state
  if (isLoading || !roster) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <Typography variant="h4" sx={{ fontWeight: 700, color: 'text.primary' }}>
            Your Fleet
          </Typography>
        </div>
        <RosterSkeleton />
      </div>
    );
  }

  // Empty state - no vehicles
  if (roster.length === 0) {
    return (
      <div className="space-y-6">
        <GlassCard>
          <div className="text-center py-12">
            <Box sx={{ color: 'primary.main', mb: 2 }}>
              <DirectionsCarRoundedIcon sx={{ fontSize: 64 }} />
            </Box>
            <h2 className="text-xl font-semibold text-slate-800 dark:text-avus mb-3">
              Welcome to MotoVaultPro
            </h2>
            <p className="text-slate-500 dark:text-titanio mb-6 max-w-md mx-auto">
              Get started by adding your first vehicle to track fuel logs, maintenance, and more
            </p>
            <Button
              variant="primary"
              size="lg"
              onClick={handleAddVehicle}
            >
              Add Your First Vehicle
            </Button>
          </div>
        </GlassCard>
      </div>
    );
  }

  // Main dashboard view
  return (
    <div className="space-y-6">
      {/* Pending Receipts Banner */}
      <PendingAssociationBanner onViewPending={() => setShowPendingReceipts(true)} />

      {/* Heading + Action Bar */}
      <div className="flex items-center justify-between">
        <Typography variant="h4" sx={{ fontWeight: 700, color: 'text.primary' }}>
          Your Fleet
        </Typography>
        <ActionBar onAddVehicle={handleAddVehicle} onLogFuel={handleLogFuel} />
      </div>

      {/* Vehicle Roster Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        {roster.map(rosterData => (
          <VehicleRosterCard
            key={rosterData.vehicle.id}
            data={rosterData}
            onClick={handleVehicleClick}
          />
        ))}
      </div>

      {/* Pending Receipts Dialog */}
      <Dialog
        open={showPendingReceipts}
        onClose={() => setShowPendingReceipts(false)}
        fullScreen={isSmall}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            maxHeight: isSmall ? '100%' : '90vh',
            m: isSmall ? 0 : 2,
          },
        }}
      >
        <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          Pending Receipts
          <IconButton
            aria-label="close"
            onClick={() => setShowPendingReceipts(false)}
            sx={{ minWidth: 44, minHeight: 44 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent sx={{ p: { xs: 1, sm: 2 } }}>
          <PendingAssociationList />
        </DialogContent>
      </Dialog>
    </div>
  );
};
