'use client';

import { useEffect, useState, useCallback } from 'react';
import dynamic from 'next/dynamic';
import { Box } from '@mui/system';
import { MapType, type RouteMarker, type CircuitMap } from '@/shared/types/Maps';
import { StatusColor } from '@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils';
import type { TripCircuitDetails, TripPointDetails } from '@/shared/types/circuit';
import { DEFAULT_SUIVIT_TRAJET_TABLE_HEAD } from '@/shared/_mock/_trajets';
import { decodePolyline } from '../../trajet/utils/maps-utils';
import FontAwesome from '@/shared/components/fontawesome';
import SvgColor from '@/shared/components/svg-color';
import { faBuilding, faClock, faUser } from '@fortawesome/free-solid-svg-icons';
import {
  containerStyles,
  InfoItem,
} from '@/shared/components/google-maps/utils/journey-summary-utils';
import { Grid } from '@mui/material';

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

interface TrajetFormProps {
  trajetId: string;
  trajet: TripCircuitDetails;
  isGoogleLoaded?: boolean;
  handleView: (item: TripCircuitDetails) => void;
}

declare global {
  interface Window {
    google: any;
  }
}

export default function DetailsDriverTrip({ trajet, isGoogleLoaded }: TrajetFormProps) {
  const [sortedData, setSortedData] = useState<TripPointDetails[]>(trajet.tripPoints);
  const [mapMarkers, setMapMarkers] = useState<RouteMarker[]>([]);
  const [routePath, setRoutePath] = useState<google.maps.LatLngLiteral[]>([]);

  useEffect(() => {
    if (trajet?.shortestPath?.routes?.length > 0 && isGoogleLoaded) {
      const mainRoute = trajet.shortestPath.routes[0];
      const decodedPath = decodePolyline(mainRoute.geometry);

      setRoutePath(decodedPath);
    } else {
      setRoutePath([]);
    }
  }, [trajet, isGoogleLoaded]);

  const getMarkerIcon = useCallback(
    (index: number, total: number) => {
      if (
        typeof window === 'undefined' ||
        !window.google ||
        !window.google.maps ||
        typeof window.google.maps.Size !== 'function' ||
        typeof window.google.maps.Point !== 'function'
      ) {
        return '/assets/icons/maps/dynamic/circuit-point.svg';
      }
      return {
        url:
          index === 0
            ? '/assets/icons/maps/dynamic/circuit-start.svg'
            : index === total - 1
              ? '/assets/icons/maps/dynamic/circuit-end.svg'
              : '/assets/icons/maps/dynamic/circuit-point.svg',
        scaledSize: new window.google.maps.Size(32, 32),
        anchor: new window.google.maps.Point(16, 32),
      };
    },
    [isGoogleLoaded]
  );

  useEffect(() => {
    if (!sortedData || sortedData.length === 0 || !isGoogleLoaded) {
      setMapMarkers([]);
      return;
    }
    const newMarkers = sortedData
      .map((point, index) => {
        const coords = point.passengerDetailsTrip?.startCoordinates;
        if (!coords) return null;
        const lat = coords.latitude;
        const lng = coords.longitude;
        if (isNaN(lat) || isNaN(lng)) return null;
        return {
          id: point.id || `point-${index + 1}`,
          position: { lat, lng },
          title:
            point.passengerDetailsTrip?.fullName ||
            point.passengerDetailsTrip?.establishmentName ||
            `Point ${index + 1}`,
          icon: getMarkerIcon(index, sortedData.length),
          color: StatusColor.PRIMARY,
        } as RouteMarker;
      })
      .filter((marker): marker is RouteMarker => marker !== null);
    setMapMarkers(newMarkers);
  }, [sortedData, getMarkerIcon, isGoogleLoaded]);

  const mapRoutes: CircuitMap[] =
    routePath.length > 0
      ? [
          {
            id: trajet.id || 'current',
            name: 'Current Route',
            color: StatusColor.PRIMARY,
            path: routePath,
            startPoint: mapMarkers[0]
              ? {
                  position: mapMarkers[0].position,
                  title: mapMarkers[0].title,
                }
              : undefined,
            endPoint:
              mapMarkers.length > 0
                ? {
                    position: mapMarkers[mapMarkers.length - 1].position,
                    title: mapMarkers[mapMarkers.length - 1].title,
                  }
                : undefined,
            users: mapMarkers.slice(1, -1).map((marker) => ({
              id: marker.id,
              position: marker.position,
              title: marker.title,
            })),
          },
        ]
      : [];

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ width: '100%', mt: 2 }}>
        <Grid container spacing={2}>
          <Grid item xs={12} md={3}>
            <InfoItem
              icon={
                <SvgColor
                  src="/assets/icons/ic_date.svg"
                  sx={{ color: 'primary.main', width: 16, height: 16 }}
                />
              }
              label="Heure de départ :"
              value={trajet.tripHour ? `${trajet.tripHour}` : 'N/A'}
            />
          </Grid>

          <Grid item xs={12} md={3}>
            <InfoItem
              icon={<FontAwesome icon={faClock} color="primary.main" width={16} />}
              label="Durée :"
              value={trajet.duration ? `${trajet.duration} min` : 'N/A'}
            />
          </Grid>

          <Grid item xs={12} md={3}>
            <InfoItem
              icon={
                <SvgColor
                  src="/assets/icons/menu/ic_exploitation.svg"
                  sx={{ color: 'primary.main', width: 16, height: 16 }}
                />
              }
              label="Distance :"
              value={trajet.distanceKm ? `${trajet.distanceKm.toFixed(2)} km` : 'N/A'}
            />
          </Grid>

          <Grid item xs={12} md={3}>
            <InfoItem
              icon={<FontAwesome icon={faUser} color="primary.main" width={16} />}
              label="Nombre d'usagers :"
              value={trajet.tripPoints ? trajet.tripPoints.length.toString() : 'N/A'}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <InfoItem
              icon={<FontAwesome icon={faBuilding} color="primary.main" width={16} />}
              label="Établissement :"
              value={trajet.tripPoints?.[0]?.passengerDetailsTrip?.establishmentName || 'N/A'}
            />
          </Grid>
        </Grid>
      </Box>

      <Box
        sx={{ height: '460px', width: '100%', mt: 2, border: '1px solid #e0e0e0', borderRadius: 1 }}
      >
        <MapView
          height="460px"
          width="100%"
          Submodule={MapType.CIRCUIT}
          routes={mapRoutes}
          markers={mapMarkers}
          defaultCenter={{ lat: 43.2965, lng: 5.3798 }}
          defaultZoom={14}
          options={{
            zoomControl: true,
            streetViewControl: false,
            mapTypeControl: false,
            fullscreenControl: true,
            styles: [
              {
                featureType: 'poi',
                elementType: 'labels',
                stylers: [{ visibility: 'off' }],
              },
            ],
          }}
        />
      </Box>
    </Box>
  );
}
