import {
  useEffect,
  useState,
  forwardRef,
  useRef,
  useLayoutEffect,
} from "react";
import { observer } from "mobx-react-lite";
import { useGeolocationStore } from "../../stores";
import { apiStore } from "../../api/ApiStore/store";
import { useClickDetection } from "../../hooks/useClickDetection";
import { OverlayScrollbarsWrapper } from "../OverlayScrollbarsWrapper";
import "../../styles/OverlayScrollbars.css";
import { getSightStations } from "../../api/ApiStore/api";
import busIcon from "../../assets/transport-icons/bus.svg";
import metroBlueIcon from "../../assets/transport-icons/metroBlue.svg";
import metroGreenIcon from "../../assets/transport-icons/metroGreen.svg";
import metroOrangeIcon from "../../assets/transport-icons/metroOrange.svg";
import metroPurpleIcon from "../../assets/transport-icons/metroPurple.svg";
import metroRedIcon from "../../assets/transport-icons/metroRed.svg";
import trainIcon from "../../assets/transport-icons/train.svg";
import tramIcon from "../../assets/transport-icons/tram.svg";
import trolleyIcon from "../../assets/transport-icons/trolley.svg";

const StationItem = ({
  station,
  handlePointerDown,
  handlePointerUp,
  handleStationClick,
  selectedStationId,
  transferIcons,
  getNoTransfersMessage,
  isLast,
}) => {
  const containerRef = useRef(null);
  const textRef = useRef(null);
  const [shouldAnimate, setShouldAnimate] = useState(false);

  useLayoutEffect(() => {
    const checkWidth = () => {
      if (containerRef.current && textRef.current) {
        const containerWidth = containerRef.current.offsetWidth;
        const textWidth = textRef.current.scrollWidth;
        const threshold = containerWidth * 1.1;
        setShouldAnimate(textWidth > threshold);
      }
    };

    checkWidth();
    window.addEventListener("resize", checkWidth);
    return () => window.removeEventListener("resize", checkWidth);
  }, [station.name]);

  return (
    <div
      style={{
        borderBottom: !isLast ? "1px solid rgba(255, 255, 255, 0.2)" : "none",
        paddingBottom: !isLast ? "8px" : "0",
        marginBottom: !isLast ? "4px" : "0",
      }}
    >
      <div
        ref={containerRef}
        className="side-menu-sight"
        onPointerDown={(e) => handlePointerDown(e, station.id)}
        onPointerUp={(e) => handlePointerUp(e, station.id, handleStationClick)}
      >
        <span ref={textRef} className={shouldAnimate ? "marquee-text" : ""}>
          {station.name}
        </span>
      </div>
      <div
        className={`side-menu-sight-transfer-list ${
          selectedStationId === station.id ? "open" : ""
        }`}
      >
        {station.transfers != null &&
        !Object.values(station.transfers).every((value) => value === "") ? (
          Object.entries(station.transfers).map(
            ([transferType, transferValue]) => {
              const IconComponent = transferIcons[transferType];

              if (transferValue && transferValue.length > 0) {
                return (
                  <div key={transferType} className="side-menu-sight-transfer">
                    {IconComponent && (
                      <img
                        style={{
                          width: "24px",
                          height: "24px",
                          marginRight: "8px",
                        }}
                        src={IconComponent}
                        alt={`${transferType} Icon`}
                      />
                    )}
                    {transferValue}
                  </div>
                );
              }
              return null;
            }
          )
        ) : (
          <div className="side-menu-sight-transfer-empty">
            {getNoTransfersMessage()}
          </div>
        )}
      </div>
    </div>
  );
};

const SightStationsList = observer(
  forwardRef(
    ({ style, className, onClose, sightId, selectedLanguage }, ref) => {
      const [stationList, setStationList] = useState([]);
      const [error, setError] = useState(null);
      const [isStationListLoading, setIsStationListLoading] = useState(true);
      const [selectedStationId, setSelectedStationId] = useState(null);

      const { handlePointerDown, handlePointerUp, handleScroll } =
        useClickDetection();

      const getNoTransfersMessage = () => {
        if (selectedLanguage === "ru") return "Нет пересадок";
        if (selectedLanguage === "zh") return "没有转移";
        return "No transfers";
      };

      const transferIcons = {
        metro_red: metroRedIcon,
        metro_green: metroGreenIcon,
        metro_blue: metroBlueIcon,
        metro_orange: metroOrangeIcon,
        metro_purple: metroPurpleIcon,
        tram: tramIcon,
        trolleybus: trolleyIcon,
        bus: busIcon,
        train: trainIcon,
      };

      useEffect(() => {
        async function fetchStationList() {
          if (!sightId) {
            setIsStationListLoading(false);
            return;
          }

          setIsStationListLoading(true);
          setError(null);
          try {
            const response = await getSightStations(sightId, selectedLanguage);

            const sortedStations = [...(response || [])].sort((a, b) => {
              const nameA = a.name.trim();
              const nameB = b.name.trim();

              return nameA.localeCompare(
                nameB,
                selectedLanguage === "ru"
                  ? "ru"
                  : selectedLanguage === "zh"
                  ? "zh"
                  : "en",
                {
                  sensitivity: "base",
                }
              );
            });

            setStationList(sortedStations);
          } catch (err) {
            setError(
              "Не удалось получить остановки. Пожалуйста, попробуйте позже."
            );
            setStationList([]);
          } finally {
            setIsStationListLoading(false);
          }
        }

        fetchStationList();
      }, [sightId, selectedLanguage]);

      const handleStationClick = (stationId) => {
        setSelectedStationId((prevId) =>
          prevId === stationId ? null : stationId
        );
      };

      return (
        <div style={style} className={`side-menu-sights ${className || ""}`}>
          <div
            className="side-menu-sights-title"
            onPointerUp={() => {
              if (onClose) {
                onClose();
              }
            }}
          >
            <p>
              {selectedLanguage === "ru"
                ? "Остановки"
                : selectedLanguage === "zh"
                ? "车站"
                : "Stations"}
            </p>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="21"
              height="12"
              viewBox="0 0 21 12"
              fill="none"
              style={{
                transform: "translateY(-50%) rotate(180deg)",
                position: "absolute",
                right: "20px",
                top: "50%",
                transition: "transform 0.15s ease-in-out",
              }}
            >
              <g clipPath="url(#clip0_658_91932)">
                <path
                  d="M10.4257 3.53158C10.2908 3.71878 10.2229 3.84702 10.1248 3.9453C7.63081 6.43048 5.13303 8.91098 2.63903 11.3962C2.19286 11.8408 1.67878 12.0186 1.06565 11.8361C0.0337182 11.5281 -0.339817 10.2776 0.349713 9.45295C0.425175 9.36309 0.510069 9.28165 0.593077 9.19928C3.45496 6.35279 6.31778 3.50537 9.18060 0.659815C10.0654 -0.219125 10.854 -0.218188 11.7397 0.661687C14.6365 3.54 17.538 6.41457 20.4196 9.30786C20.6706 9.55966 20.88 9.91441 20.962 10.2561C21.1167 10.9019 20.7781 11.515 20.2131 11.8193C19.6462 12.1263 18.9387 12.0392 18.4482 11.5806C18.0709 11.2286 17.7125 10.8561 17.3474 10.491C15.1439 8.29601 12.9405 6.10193 10.7389 3.90599C10.6559 3.82362 10.5889 3.72721 10.4267 3.53158L10.4257 3.53158Z"
                  fill="white"
                />
              </g>
              <defs>
                <clipPath id="clip0_658_91932">
                  <rect
                    width="21"
                    height="12"
                    fill="white"
                    transform="translate(21 12) rotate(-180)"
                  />
                </clipPath>
              </defs>
            </svg>
          </div>
          <OverlayScrollbarsWrapper
            className="side-menu-sights-block"
            ref={ref}
            onScroll={handleScroll}
          >
            {isStationListLoading ? (
              <div>
                {selectedLanguage === "ru"
                  ? "Загрузка остановок..."
                  : selectedLanguage === "zh"
                  ? "加载停止..."
                  : "Loading stops..."}
              </div>
            ) : error ? (
              <div className="error-message">{error}</div>
            ) : stationList.length === 0 ? (
              <div>
                {selectedLanguage === "ru"
                  ? "Остановки не найдены"
                  : selectedLanguage === "zh"
                  ? "没有找到停靠站"
                  : "No stops found"}
              </div>
            ) : (
              stationList.map((station, index) => (
                <StationItem
                  key={station.id}
                  station={station}
                  handlePointerDown={handlePointerDown}
                  handlePointerUp={handlePointerUp}
                  handleStationClick={handleStationClick}
                  selectedStationId={selectedStationId}
                  transferIcons={transferIcons}
                  getNoTransfersMessage={getNoTransfersMessage}
                  isLast={index === stationList.length - 1}
                />
              ))
            )}
          </OverlayScrollbarsWrapper>
        </div>
      );
    }
  )
);

export default SightStationsList;
