"use client";

import React, { useEffect, useMemo, useCallback, useState } from "react";
import { Marker } from "@react-google-maps/api";
import { type RouteMarker, type MarkerType, MapType } from "@/shared/types/Maps";
import { DetailsPopover } from "../custom-popover/DetailsPopover";
import { StatusColor } from "@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils";
import CustomPopover, { usePopover } from "../custom-popover";
import { IconButton, Typography } from "@mui/material";
import { DEFAULT_POPOVER_DATA, getColoredSVG } from "./utils/map-marker";
import CustomTooltip from "../tooltips/tooltip-custom";
import FontAwesome from "../fontawesome";
import { faCheck, faEyeSlash, faPenToSquare } from "@fortawesome/free-solid-svg-icons";
import { iconButtonStyles } from "@/shared/theme/css";
import { Stack } from "@mui/system";

interface MapMarkerProps {
  marker: RouteMarker & { isVisited?: boolean };
  selectedMarker: MarkerType | null;
  setSelectedMarker: (id: MarkerType | null) => void;
  Submodule: MapType;
}

function MapMarker({ marker, selectedMarker, setSelectedMarker, Submodule }: MapMarkerProps) {
  const popover = usePopover();
  const [iconConfig, setIconConfig] = useState<google.maps.Icon | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isClickPopover, setIsClickPopover] = useState(false);

  const markerType = useMemo(
    () => ({
      isToll: marker.id.toString().startsWith("toll-"),
      isUser: marker.id.toString().startsWith("user-"),
      isStart: marker.id.toString().startsWith("start-"),
      isEnd: marker.id.toString().startsWith("end-"),
      isStartOrEnd: marker.id.toString().startsWith("start-") || marker.id.toString().startsWith("end-"),
    }),
    [marker.id]
  );

  const isDriver = Submodule === MapType.DRIVER;
  const isPassenger = Submodule === MapType.PASSENGER;
  const isDriverStart = isDriver && markerType.isStart;
  const isPassengerModule = isPassenger && markerType.isUser;

  const zIndex = useMemo(() => (selectedMarker === marker.id ? 1000 : 1), [selectedMarker, marker.id]);

  useEffect(() => {
    const loadIcon = async () => {
      try {
        if (markerType.isUser && marker.isVisited) {
          setIconConfig({
            url: '/assets/icons/maps/dynamic/usager-visited.svg',
            scaledSize: new google.maps.Size(36, 36),
            anchor: new google.maps.Point(18, 18),
          });
          return;
        }

        const defaultColor = marker.color || "#FFA500";
        let iconUrl: string;

        if (markerType.isToll) {
          iconUrl = marker.icon || "/placeholder.svg";
        } else {
          let svgType = "usager-location";
          if (markerType.isStart) {
            svgType = isDriver ? "driver-location" : "circuit-start";
          } else if (markerType.isEnd) {
            svgType = isDriver ? "establishment" : "circuit-end";
          }
          iconUrl = await getColoredSVG(svgType, defaultColor);
        }

        setIconConfig({
          url: iconUrl,
          scaledSize: new google.maps.Size(36, 36),
          anchor: new google.maps.Point(18, 18),
        });
      } catch (error) {
        setIconConfig({
          url: "/placeholder.svg",
          scaledSize: new google.maps.Size(36, 36),
          anchor: new google.maps.Point(18, 18),
        });
      } finally {
        setIsLoading(false);
      }
    };

    loadIcon();
  }, [marker.icon, marker.color, markerType, isDriver, marker.isVisited]);

  const handleMarkerMouseOver = useCallback(
    (event: google.maps.MapMouseEvent) => {
      if (isDriverStart) return; 

      if (isPassengerModule && markerType.isUser && isClickPopover) return; 

      setSelectedMarker(marker.id);
      const markerElement = event.domEvent.target as HTMLElement;
      popover.setOpen(markerElement); 
    },
    [marker.id, setSelectedMarker, popover, isDriverStart, isPassengerModule, markerType.isUser, isClickPopover]
  );

  const handleMarkerMouseOut = useCallback(() => {
    if ((isDriverStart || (isPassengerModule && markerType.isUser)) && isClickPopover) return; 

    setSelectedMarker(null);
    popover.onClose(); 
  }, [setSelectedMarker, popover, isDriverStart, isPassengerModule, markerType.isUser, isClickPopover]);

  const handleMarkerClick = useCallback(
    (event: google.maps.MapMouseEvent) => {
      if (isDriverStart || isPassengerModule) {
        setSelectedMarker(marker.id);
        const markerElement = event.domEvent.target as HTMLElement;
        popover.setOpen(markerElement);
        setIsClickPopover(true);
      }
    },
    [isDriverStart, isPassengerModule, setSelectedMarker, marker.id, popover]
  );

  const renderActionButtons = () => (
    <Stack direction="row" spacing={1}>
      <CustomTooltip title="Hide">
        <IconButton sx={iconButtonStyles} size="small">
          <FontAwesome icon={faEyeSlash} />
        </IconButton>
      </CustomTooltip>
      <CustomTooltip title="Edit">
        <IconButton sx={iconButtonStyles} size="small">
          <FontAwesome icon={faPenToSquare} />
        </IconButton>
      </CustomTooltip>
    </Stack>
  );

  const renderPopover = () => {
    if (isLoading || !selectedMarker || selectedMarker !== marker.id) return null;

    const popoverProps = {
      open: popover.open,
      onClose: () => {
        popover.onClose();
        if (isClickPopover) setIsClickPopover(false);
      },
      sx: { borderRadius: 3, p: 1 },
    };

    if (markerType.isStartOrEnd) {
      return (
        <CustomPopover {...popoverProps} isHover={!isDriverStart}>
          {isDriverStart ? (
            renderActionButtons()
          ) : (
            <Typography
              sx={{
                fontSize: "0.875rem",
                color: "primary.main",
                fontWeight: (theme) => theme.typography.fontWeightMedium,
              }}
            >
              {marker.title} {"(200km)"}
            </Typography>
          )}
        </CustomPopover>
      );
    }

    if (markerType.isUser) {
      const popoverData = [...DEFAULT_POPOVER_DATA];
      if (marker.isVisited) {
        popoverData.push({ icon: faCheck, value: "Visité" });
      }

      if (isPassengerModule) {
        if (isClickPopover) {
          return <CustomPopover {...popoverProps} isHover={false}>{renderActionButtons()}</CustomPopover>;
        } else {
          return (
            <DetailsPopover
              anchorEl={popover.open}
              onClose={popover.onClose}
              color={marker.color || StatusColor.PRIMARY}
              data={popoverData}
              arrow={false}
            />
          );
        }
      } else {
        return (
          <DetailsPopover
            anchorEl={popover.open}
            onClose={popover.onClose}
            color={marker.color || StatusColor.PRIMARY}
            data={popoverData}
            arrow={false}
          />
        );
      }
    }

    return null;
  };

  if (isLoading || !iconConfig) return null;

  const markerOptions = {
    position: marker.position,
    icon: iconConfig,
    zIndex,
    key: `${marker.id}-${marker.isVisited ? 'visited' : 'not-visited'}`,
  };

  return (
    <>
      <Marker
        {...markerOptions}
        onMouseOver={handleMarkerMouseOver}
        onMouseOut={handleMarkerMouseOut}
        onClick={handleMarkerClick}
      />
      {renderPopover()}
    </>
  );
}

export default React.memo(MapMarker);
