import { useState, useEffect, useMemo, useCallback } from 'react';
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Typography, Box, useTheme } from '@mui/material';
import { IGeolocItem, GeolocStatus } from '@/shared/types/geoloc';
import dynamic from 'next/dynamic';
import { MapType } from '@/shared/types/Maps';
import { GeolocStatusChip, getGeolocStatusLabel } from '../styles';
import { RouteSummary } from '@/shared/components/google-maps/route-summary';

const MapView = dynamic(() => import('@/shared/components/google-maps/maps'), {
  ssr: false,
});

type Props = {
  open: boolean;
  onClose: () => void;
  geolocItem: IGeolocItem;
};

export default function GeolocDetailDialog({ open, onClose, geolocItem }: Props) {
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  const [directionsResponses, setDirectionsResponses] = useState<Record<string, google.maps.DirectionsResult>>({});
  const [vehiclePositions, setVehiclePositions] = useState<Record<string, any>>({});
  const theme = useTheme();

  const routesForMap = useMemo(() => {
    if (!geolocItem.routes) return [];

    return geolocItem.routes.map((route) => ({
      ...route,
      departureDate: geolocItem.dateDepart,
      arrivalDate: geolocItem.dateArrivee,
      vehicule: geolocItem.vehicule,
      vehiculeId: geolocItem.vehiculeId,
      status: GeolocStatus.IN_PROGRESS,
      departement: geolocItem.departement,
      prenomChauffeur: geolocItem.prenomChauffeur,
      nomChauffeur: geolocItem.nomChauffeur,
      id: route.id || `route-${geolocItem.id}`,
      startPoint: {
        position: route.path?.[0] || { lat: 0, lng: 0 },
        title: geolocItem.adresseDepart || 'Départ'
      },
      endPoint: {
        position: route.path?.[route.path?.length - 1] || { lat: 0, lng: 0 },
        title: geolocItem.adresseArrivee || 'Arrivée'
      },
      path: route.path || []
    }));
  }, [geolocItem]);

  const handleMapLoaded = useCallback(() => {
    setIsMapLoaded(true);
  }, []);

  const handleDirectionsUpdate = useCallback((responses: Record<string, google.maps.DirectionsResult>) => {
    setDirectionsResponses(responses);
  }, []);

  const handleVehiclePositionsUpdate = useCallback((positions: Record<string, any>) => {
    setVehiclePositions(positions);
  }, []);

  const getStatusLabel = (status: GeolocStatus) => {
    switch (status) {
      case GeolocStatus.IN_PROGRESS:
        return 'En cours';
      case GeolocStatus.COMPLETED:
        return 'Terminé';
      case GeolocStatus.PLANNED:
        return 'Planifié';
      case GeolocStatus.FAILED:
        return 'Échoué';
      default:
        return 'Inconnu';
    }
  };

  const formattedDepartDate = geolocItem.dateDepart
    ? new Date(geolocItem.dateDepart).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
    : '-';

  const formattedDepartTime = geolocItem.dateDepart
    ? new Date(geolocItem.dateDepart).toLocaleTimeString('fr-FR', {
      hour: '2-digit',
      minute: '2-digit',
    })
    : '-';

  const formattedArrivalDate = geolocItem.dateArrivee
    ? new Date(geolocItem.dateArrivee).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
    : '-';

  const formattedArrivalTime = geolocItem.dateArrivee
    ? new Date(geolocItem.dateArrivee).toLocaleTimeString('fr-FR', {
      hour: '2-digit',
      minute: '2-digit',
    })
    : '-';

  const calculateDuration = () => {
    const isCompleted = geolocItem.status === GeolocStatus.COMPLETED;
    if (isCompleted && geolocItem.dateDepart && geolocItem.dateArrivee) {
      const start = new Date(geolocItem.dateDepart);
      const end = new Date(geolocItem.dateArrivee);
      const diffMs = end.getTime() - start.getTime();
      const diffHrs = Math.floor(diffMs / (1000 * 60 * 60));
      const diffMins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
      return `${diffHrs}h ${diffMins}min`;
    }
    return geolocItem.duree || '-';
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="lg"
      fullWidth
      PaperProps={{
        sx: {
          height: '90vh',
          maxHeight: '90vh',
          display: 'flex',
          flexDirection: 'column',
        },
      }}
    >
      <DialogTitle>
        <Typography
          variant="h5"
          component="div"
          sx={{ display: 'flex', alignItems: 'center', color: 'primary.main', fontWeight: 'bold' }}
        >
          Détails du trajet
          <Box sx={{ ml: 2 }}>
            <GeolocStatusChip theme={theme} label={getGeolocStatusLabel(geolocItem.status)} status={geolocItem.status} />
          </Box>
        </Typography>
      </DialogTitle>
      <DialogContent
        dividers
        sx={{
          flexGrow: 1,
          display: 'flex',
          flexDirection: 'column',
          p: 2,
          '&::-webkit-scrollbar': {
            width: '8px',
            height: '8px',
          },
          '&::-webkit-scrollbar-thumb': {
            backgroundColor: 'rgba(0,0,0,0.2)',
            borderRadius: '4px',
            visibility: 'hidden',
          },
          '&:hover::-webkit-scrollbar-thumb': {
            visibility: 'visible',
          },
        }}
      >
        <Box sx={{ mb: 2 }}>
          <RouteSummary
            distance={`${geolocItem.distance || '-'} km`}
            duration={calculateDuration()}
            departDate={formattedDepartDate}
            departTime={formattedDepartTime}
            arrivalDate={formattedArrivalDate}
            arrivalTime={formattedArrivalTime}
            vehicleInfo={{
              vehicleId: geolocItem.vehiculeId || '-',
              vehicleName: geolocItem.vehicule || '-',
              driverName: `${geolocItem.prenomChauffeur || ''} ${geolocItem.nomChauffeur || ''}`.trim() || '-',
            }}
            departureAddress={geolocItem.adresseDepart || '-'}
            arrivalAddress={geolocItem.adresseArrivee || '-'}
            agency={geolocItem.agence || '-'}
            department={geolocItem.departement || '-'}
            sector={geolocItem.secteur || '-'}
            averageSpeed={`${geolocItem.vitesseMoyenne || '-'} km/h`}
            consumption={`${geolocItem.consommation || '-'} L/100km`}
            status={getStatusLabel(geolocItem.status)}
            statusCode={geolocItem.status}
            showAllInfo={true}
            hideTitle={true}
            useNewLayout={true}
          />
        </Box>

        <Box sx={{ height: '400px', width: '100%', marginTop: 2 }}>
          {routesForMap.length > 0 ? (
            <MapView
              height="400px"
              routes={routesForMap}
              Submodule={MapType.GEOLOC}
              isGeoloc={true}
              activeDepartement={geolocItem.departement}
              vehiclePositions={vehiclePositions}
              onDirectionsUpdate={handleDirectionsUpdate}
              onMapLoaded={handleMapLoaded}
              onVehiclePositionsUpdate={handleVehiclePositionsUpdate}
              selectedVehicule={geolocItem.vehiculeId || ''}
              selectedChauffeur={`${geolocItem.prenomChauffeur || ''} ${geolocItem.nomChauffeur || ''}`}
            />
          ) : (
            <Box
              sx={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                bgcolor: 'background.neutral',
                borderRadius: 1,
              }}
            >
              <Typography variant="body1" color="text.secondary">
                Aucun itinéraire disponible
              </Typography>
            </Box>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} variant="outlined">
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  );
}