import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dynamic from 'next/dynamic';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Typography,
  Box,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Button,
  CircularProgress,
} from '@mui/material';
import { MapType } from '@/shared/types/Maps';
import { IGeolocHistory } from '@/shared/types/geoloc';
import { StatusColor } from '@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils';
import { GeolocSummary } from './geoloc-summary';
import { BaseStyledRow } from '@/shared/sections/contract/styles';
import { HeaderCell } from '@/shared/components/form/style';
import { useGeolocHistoryStore } from '@/shared/api/stores/geolocHistory';

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

type Props = {
  onClose: () => void;
  historyId: number | null;
};

export default function GeolocDetailHistoryDialog({ onClose, historyId }: Props) {
  const { getGeolocDataById, geolocDataTrips, loading } = useGeolocHistoryStore();
  const [selectedTripIndex, setSelectedTripIndex] = useState<number | null>(null);
  const [directionsResponses, setDirectionsResponses] = useState<
    Record<string, google.maps.DirectionsResult>
  >({});
  const [vehiclePositions, setVehiclePositions] = useState<Record<string, any>>({});

  const [open, setOpen] = useState(false);
 
  useEffect(() => {
    if (historyId === null) return;

    if (!geolocDataTrips || Number(geolocDataTrips.id) !== historyId) {
      getGeolocDataById(historyId);
    } else {
      setOpen(true);
    }
  }, [historyId, geolocDataTrips]);

  useEffect(() => {
    if (historyId !== null && geolocDataTrips && Number(geolocDataTrips.id) === historyId) {
      setOpen(true);
    }
  }, [geolocDataTrips, historyId]);

  const handleClose = () => {
    setOpen(false);
    onClose();
  };
  useEffect(() => {
    if (geolocDataTrips?.trips?.length) {
      setSelectedTripIndex(0);
    }
  }, [geolocDataTrips]);

  const selectedTrip =
    selectedTripIndex !== null ? geolocDataTrips?.trips[selectedTripIndex] : null;

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="lg" fullWidth>
      <DialogTitle sx={{ fontWeight: 'bold', color: 'primary.main' }}>
        Détails du trajet
      </DialogTitle>
      <DialogContent dividers sx={{ minHeight: 400 }}>
        {loading ? (
          <Box
            sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}
          >
            <CircularProgress size={64} />
          </Box>
        ) : !geolocDataTrips ? (
          <Typography align="center" sx={{ mt: 4 }}>
            Aucun détail disponible.
          </Typography>
        ) : (
          <>
            <Box sx={{ mb: 2 }}>
              <GeolocSummary
                date={new Date(geolocDataTrips.tripDate).toLocaleDateString('fr-FR')}
                vehicleInfo={{
                  vehicleId: geolocDataTrips.carRegistration,
                  driverName: geolocDataTrips.driverName,
                }}
                agency={geolocDataTrips.agence}
                department={geolocDataTrips.departement}
                sector={geolocDataTrips.secteur}
                showAllInfo={true}
              />
            </Box>

            <Typography variant="h6" sx={{ mt: 2, mb: 1 }} color="primary.main">
              Liste des trajets
            </Typography>

            <Table size="small">
              <TableHead>
                <BaseStyledRow>
                  {[
                    'Durée',
                    'Distance',
                    'Départ',
                    'Arrivée',
                    'Adresse Départ',
                    'Adresse Arrivée',
                    'Vitesse Moyenne',
                  ].map((label, idx) => (
                    <HeaderCell
                      key={idx}
                      sx={{ backgroundColor: 'primary.lighter', py: 1.5, textAlign: 'center' }}
                    >
                      {label}
                    </HeaderCell>
                  ))}
                </BaseStyledRow>
              </TableHead>
              <TableBody>
                {geolocDataTrips.trips.map((trip, index) => (
                  <TableRow
                    key={trip.id}
                    hover
                    selected={index === selectedTripIndex}
                    onClick={() => {
                      setSelectedTripIndex(index);
                    }}
                    sx={{ cursor: 'pointer' }}
                  >
                    <TableCell align="center">{trip.duration}</TableCell>
                    <TableCell align="center">{trip.distance} km</TableCell>
                    <TableCell align="center">{trip.startHour}</TableCell>
                    <TableCell align="center">{trip.endHour}</TableCell>
                    <TableCell align="center">{trip.departure_address}</TableCell>
                    <TableCell align="center">{trip.arrival_address}</TableCell>
                    <TableCell align="center">{trip.avg_speed} km/h</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            <Box sx={{ height: 400, width: '100%', mt: 2 }}>
              {selectedTrip ? (
                <MapView trip={selectedTrip} height="400px" width="100%" />
              ) : (
                <Box
                  sx={{
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Typography>Aucun itinéraire sélectionné</Typography>
                </Box>
              )}
            </Box>
          </>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} variant="outlined">
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  );
}
