"use client";

import React, { useState, useMemo, useCallback } from "react";
import { Box, CircularProgress, Avatar, Badge, Chip, Stack, Divider } from "@mui/material";
import { GoogleMap, useJsApiLoader, Marker } from "@react-google-maps/api";
import { DriverScore } from "@/shared/types/circuit";
import { primary, success, error, warning } from "@/shared/theme/palette";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { Typography } from "@mui/material";
import { getColoredSVG } from "./utils/map-marker";
import {
  faCircleCheck,
  faCircleXmark,
  faCar,
  faWheelchair,
  faChair,
  faClock
} from "@fortawesome/free-solid-svg-icons";
import FontAwesome from "@/shared/components/fontawesome";
import ConditionalComponent from "@/shared/components/table/ConditionalComponent";

const DEFAULT_CENTER = { lat: 43.2965, lng: 5.3798 };
const DEFAULT_ZOOM = 10;
const GOOGLE_MAPS_LIBRARIES: ("places" | "geometry")[] = ["places", "geometry"];

const DAY_NAMES = ["", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"];

interface DriverMapProps {
  drivers: DriverScore[];
  selectedDriverId?: string;
  onDriverSelect?: (driverId: string) => void;
  height?: string;
}

export default function DriverMap({
  drivers,
  selectedDriverId,
  onDriverSelect,
  height = "400px",
}: DriverMapProps) {
  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY!,
    libraries: GOOGLE_MAPS_LIBRARIES,
  });

  const [map, setMap] = useState<google.maps.Map | null>(null);
  const [selectedMarker, setSelectedMarker] = useState<string | null>(null);
  const [iconUrls, setIconUrls] = useState<Record<string, string>>({});
  const popover = usePopover();

  const mapContainerStyle = useMemo(
    () => ({
      height,
      width: "100%",
    }),
    [height]
  );

  React.useEffect(() => {
    const loadIcons = async () => {
      try {
        const urls: Record<string, string> = {};
        urls.candidateNormal = await getColoredSVG("driver-location", primary.main);
        urls.candidateSelected = await getColoredSVG("driver-location", primary.dark);
        urls.driverAvailableNormal = await getColoredSVG("driver-location", "#10B981");
        urls.driverAvailableSelected = await getColoredSVG("driver-location", "#059669");
        urls.driverBusyNormal = await getColoredSVG("vehicule", "#9333EA");
        urls.driverBusySelected = await getColoredSVG("vehicule", "#7C3AED");

        setIconUrls(urls);
      } catch (error) {
      }
    };
    loadIcons();
  }, []);

  React.useEffect(() => {
    return () => {
      if (map) {
        google.maps.event.clearInstanceListeners(map);
      }
    };
  }, [map]);

  const onLoad = useCallback((map: google.maps.Map) => {
    setMap(map);

    if (drivers.length > 0) {
      const bounds = new window.google.maps.LatLngBounds();
      drivers.forEach((driver) => {
        const pos = driver.currentPosition
          ? { lat: driver.currentPosition.latitude, lng: driver.currentPosition.longitude }
          : (typeof driver.homeLat === 'number' && typeof driver.homeLng === 'number'
            ? { lat: driver.homeLat, lng: driver.homeLng }
            : null);
        if (pos) bounds.extend(pos);
      });

      if (!bounds.isEmpty()) {
        map.fitBounds(bounds);
      }
    }
  }, [drivers]);

  const handleMarkerClick = useCallback(
    (driver: DriverScore, event: google.maps.MapMouseEvent) => {
      setSelectedMarker(driver.driverId);
      if (onDriverSelect) {
        onDriverSelect(driver.driverId);
      }

      const markerElement = event.domEvent?.target as HTMLElement;
      if (markerElement) {
        popover.setOpen(markerElement);
      }
    },
    [onDriverSelect, popover]
  );

  const handleMarkerMouseOver = useCallback(
    (driver: DriverScore, event: google.maps.MapMouseEvent) => {
      setSelectedMarker(driver.driverId);
      const markerElement = event.domEvent?.target as HTMLElement;
      if (markerElement) {
        popover.setOpen(markerElement);
      }
    },
    [popover]
  );

  const handleMarkerMouseOut = useCallback(() => {
    setSelectedMarker(null);
    popover.onClose();
  }, [popover]);

  const formatWorkingHours = (workingHours: any[]) => {
    if (!workingHours || workingHours.length === 0) {
      return null;
    }
    const sortedHours = [...workingHours].sort((a, b) => a.dayOfWeek - b.dayOfWeek);

    return sortedHours.map((wh) => ({
      day: DAY_NAMES[wh.dayOfWeek] || `Jour ${wh.dayOfWeek}`,
      hours: `${wh.startHour}h - ${wh.endHour}h`,
    }));
  };

  return (
    <ConditionalComponent
      isValid={isLoaded && !!iconUrls.driverAvailableNormal && !!iconUrls.driverBusyNormal && !!iconUrls.candidateNormal}
      defaultComponent={
        <Box
          sx={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height,
            width: "100%",
            border: "1px solid",
            borderColor: "divider",
            borderRadius: 2,
          }}
        >
          <CircularProgress />
        </Box>
      }
    >
      <Box
        sx={{
          position: "relative",
          border: "1px solid",
          borderColor: "divider",
          borderRadius: 2,
          overflow: "hidden",
          height,
        }}
      >
        <GoogleMap
          mapContainerStyle={mapContainerStyle}
          center={DEFAULT_CENTER}
          zoom={DEFAULT_ZOOM}
          onLoad={onLoad}
          options={{
            disableDefaultUI: false,
            zoomControl: true,
            streetViewControl: false,
            mapTypeControl: false,
          }}
        >
          {drivers.map((driver) => {
            const pos = driver.currentPosition
              ? { lat: driver.currentPosition.latitude, lng: driver.currentPosition.longitude }
              : (typeof driver.homeLat === 'number' && typeof driver.homeLng === 'number'
                ? { lat: driver.homeLat, lng: driver.homeLng }
                : null);

            if (!pos) {
              return null;
            }

            const isSelected = selectedDriverId === driver.driverId;
            const isCandidate = driver.hasApplication === true;
            const hasCircuit = driver.hasActiveCircuit === true;
            const zIndex = isSelected ? 1000 : driver.rank ? 100 - driver.rank : 1;
            let iconUrl: string;
            if (isCandidate) {
              iconUrl = isSelected ? iconUrls.candidateSelected : iconUrls.candidateNormal;
            } else if (!hasCircuit) {
              iconUrl = isSelected ? iconUrls.driverAvailableSelected : iconUrls.driverAvailableNormal;
            } else {
              iconUrl = isSelected ? iconUrls.driverBusySelected : iconUrls.driverBusyNormal;
            }

            if (!iconUrl) {
              return null;
            }

            return (
              <Marker
                key={driver.driverId}
                position={pos}
                icon={{
                  url: iconUrl,
                  scaledSize: new google.maps.Size(isSelected ? 48 : 36, isSelected ? 48 : 36),
                  anchor: new google.maps.Point(isSelected ? 24 : 18, isSelected ? 24 : 18),
                }}
                zIndex={zIndex}
                onClick={(e) => handleMarkerClick(driver, e)}
                onMouseOver={(e) => handleMarkerMouseOver(driver, e)}
                onMouseOut={handleMarkerMouseOut}
              />
            );
          })}
        </GoogleMap>

        <ConditionalComponent isValid={!!selectedMarker}>
          <CustomPopover
            open={popover.open}
            onClose={popover.onClose}
            sx={{ borderRadius: 2, p: 0, minWidth: 320, maxWidth: 400 }}
            isHover={true}
          >
            {(() => {
              const driver = drivers.find((d) => d.driverId === selectedMarker);
              if (!driver) return null;

              const formattedWorkingHours = formatWorkingHours(driver.workingHours || []);

              return (
                <Box sx={{ p: 2 }}>
                  <Stack direction="row" alignItems="center" spacing={1.5} mb={2}>
                    <Badge
                      badgeContent={driver.rank}
                      color="primary"
                      sx={{
                        '& .MuiBadge-badge': {
                          fontSize: '0.75rem',
                          fontWeight: 'bold',
                          minWidth: 22,
                          height: 22,
                        },
                      }}
                    >
                      <Avatar
                        sx={{
                          width: 40,
                          height: 40,
                          bgcolor: primary.main,
                        }}
                      >
                        <Typography sx={{ fontSize: '1.2rem' }}>👤</Typography>
                      </Avatar>
                    </Badge>
                    <Box sx={{ flex: 1 }}>
                      <Typography
                        sx={{
                          fontSize: "0.95rem",
                          fontWeight: 'bold',
                          color: "primary.main",
                          lineHeight: 1.2,
                        }}
                      >
                        {driver.driverName}
                      </Typography>
                      <ConditionalComponent isValid={!!driver.email}>
                        <Typography sx={{ fontSize: "0.7rem", color: "text.secondary" }}>
                          {driver.email}
                        </Typography>
                      </ConditionalComponent>
                    </Box>
                  </Stack>

                  <Stack direction="row" alignItems="center" spacing={1} mb={1.5}>
                    <Typography sx={{ fontSize: "0.8rem", color: "text.secondary" }}>
                      Distance:
                    </Typography>
                    <Chip
                      label={`${driver.emptyDistanceKm.toFixed(2)} km`}
                      size="small"
                      color="primary"
                      sx={{ fontSize: "0.75rem", height: 24 }}
                    />
                  </Stack>

                  <Stack direction="row" alignItems="center" spacing={1} mb={1.5}>
                    <FontAwesome
                      icon={driver.hasActiveCircuit ? faCircleCheck : faCircleXmark}
                      style={{
                        color: driver.hasActiveCircuit ? success.main : error.light,
                        fontSize: 16
                      }}
                    />
                    <Typography sx={{ fontSize: "0.8rem", color: "text.secondary" }}>
                      {driver.hasActiveCircuit ? "Affecté à un circuit" : "Disponible"}
                    </Typography>
                  </Stack>

                  <ConditionalComponent isValid={!!driver.hasApplication}>
                    <Stack direction="row" alignItems="center" spacing={1} mb={1.5}>
                      <FontAwesome
                        icon={faCircleCheck}
                        style={{ color: warning.main, fontSize: 16 }}
                      />
                      <Typography sx={{ fontSize: "0.8rem", color: "text.secondary" }}>
                        A postulé
                      </Typography>
                    </Stack>
                  </ConditionalComponent>

                  <Divider sx={{ my: 1.5 }} />

                  <ConditionalComponent
                    isValid={!!driver.vehicle}
                    defaultComponent={
                      <Box mb={1.5}>
                        <Typography sx={{ fontSize: "0.75rem", color: "text.disabled", fontStyle: "italic" }}>
                          Aucun véhicule assigné
                        </Typography>
                      </Box>
                    }
                  >
                    <Box mb={1.5}>
                      <Stack direction="row" alignItems="center" spacing={1} mb={1}>
                        <FontAwesome icon={faCar} style={{ color: primary.main, fontSize: 14 }} />
                        <Typography
                          sx={{
                            fontSize: "0.8rem",
                            fontWeight: 600,
                            color: "text.primary",
                          }}
                        >
                          Véhicule
                        </Typography>
                      </Stack>
                      <Box sx={{ pl: 2.5 }}>
                        <Typography sx={{ fontSize: "0.75rem", color: "text.secondary", mb: 0.5 }}>
                          {driver.vehicle?.vehiculeName}
                        </Typography>
                        <Stack direction="row" spacing={1.5}>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <FontAwesome icon={faChair} style={{ fontSize: 12, color: primary.main }} />
                            <Typography sx={{ fontSize: "0.7rem", color: "text.secondary" }}>
                              {driver.vehicle?.seatCount} places
                            </Typography>
                          </Stack>
                          <ConditionalComponent isValid={!!driver.vehicle && driver.vehicle.wheelchairSeats > 0}>
                            <Stack direction="row" alignItems="center" spacing={0.5}>
                              <FontAwesome icon={faWheelchair} style={{ fontSize: 12, color: primary.main }} />
                              <Typography sx={{ fontSize: "0.7rem", color: "text.secondary" }}>
                                {driver.vehicle?.wheelchairSeats} PMR
                              </Typography>
                            </Stack>
                          </ConditionalComponent>
                        </Stack>
                      </Box>
                    </Box>
                  </ConditionalComponent>

                  <ConditionalComponent
                    isValid={!!formattedWorkingHours && formattedWorkingHours.length > 0}
                    defaultComponent={
                      <Box>
                        <Divider sx={{ my: 1.5 }} />
                        <Typography sx={{ fontSize: "0.7rem", color: "text.disabled", fontStyle: "italic" }}>
                          Aucun emploi du temps défini
                        </Typography>
                      </Box>
                    }
                  >
                    <Box>
                      <Divider sx={{ my: 1.5 }} />
                      <Stack direction="row" alignItems="center" spacing={1} mb={1}>
                        <FontAwesome icon={faClock} style={{ color: primary.main, fontSize: 14 }} />
                        <Typography
                          sx={{
                            fontSize: "0.8rem",
                            fontWeight: 600,
                            color: "text.primary",
                          }}
                        >
                          Emploi du temps
                        </Typography>
                      </Stack>
                      <Box sx={{ pl: 2.5 }}>
                        {formattedWorkingHours?.map((wh, index) => (
                          <Stack
                            key={index}
                            direction="row"
                            justifyContent="space-between"
                            sx={{ mb: 0.5 }}
                          >
                            <Typography sx={{ fontSize: "0.7rem", color: "text.secondary" }}>
                              {wh.day}
                            </Typography>
                            <Typography
                              sx={{
                                fontSize: "0.7rem",
                                color: "text.primary",
                                fontWeight: 500,
                              }}
                            >
                              {wh.hours}
                            </Typography>
                          </Stack>
                        ))}
                      </Box>
                    </Box>
                  </ConditionalComponent>
                </Box>
              );
            })()}
          </CustomPopover>
        </ConditionalComponent>
      </Box>
    </ConditionalComponent>
  );
}