import React, { useState, useEffect } from "react";
import "../../styles/TransferWidget.css";
import { observer } from "mobx-react-lite";
import { useGeolocationStore } from "../../stores";
import { apiStore } from "../../api/ApiStore/store";
import { getTargetStation } from "../../utils/routeStationsUtils";
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 TransferWidget = observer(function TransferWidget({
  isOpen,
  selectedLanguageRight,
}) {
  const { nearestStationId, currentStationId, setCurrentStationId } =
    useGeolocationStore();
  const {
    routeStations,
    routeStationsEn,
    routeStationsZh,
    orderedRouteStations,
    context,
    route,
  } = apiStore;
  const [currentTransferData, setCurrentTransferData] = useState(null);

  useEffect(() => {
    if (nearestStationId != null) {
      setCurrentStationId(nearestStationId);
    }
  }, [nearestStationId, setCurrentStationId]);

  useEffect(() => {
    if (!routeStations || !context?.currentCoordinates) {
      setCurrentTransferData(null);
      return;
    }

    let targetStation = null;
    let targetStationId = null;

    if (nearestStationId != null) {
      targetStation = routeStations.find((s) => s.id == nearestStationId);
      targetStationId = nearestStationId;
    } else if (
      orderedRouteStations &&
      orderedRouteStations.length > 0 &&
      route?.path
    ) {
      targetStation = getTargetStation(
        context.currentCoordinates,
        orderedRouteStations,
        route.path
      );

      if (targetStation) {
        targetStationId = targetStation.id;
      }
    }

    if (targetStation) {
      setCurrentTransferData(targetStation.transfers);
      setCurrentStationId(targetStationId);
    } else {
      setCurrentTransferData(null);
      setCurrentStationId(null);
    }
  }, [
    nearestStationId,
    routeStations,
    orderedRouteStations,
    route?.path,
    context?.currentCoordinates,
  ]);

  let stationName = null;
  if (currentStationId != null) {
    const stationsByLang =
      selectedLanguageRight === "ru"
        ? routeStations
        : selectedLanguageRight === "en"
        ? routeStationsEn
        : routeStationsZh;

    const station =
      stationsByLang &&
      stationsByLang.find((s) => String(s.id) === String(currentStationId));
    stationName = station ? station.name : null;
  }

  const getTransferLabel = () => {
    if (!stationName) {
      if (selectedLanguageRight === "en") return "Nearest station not found";
      if (selectedLanguageRight === "zh") return "最近的站点未找到";
      return "Ближайшая остановка не обнаружена";
    }

    if (selectedLanguageRight === "en") {
      return (
        <>
          Transfer at stop<br />
          «{stationName}»:
        </>
      );
    }

    if (selectedLanguageRight === "zh") {
      return (
        <>
          换乘站<br />
          «{stationName}»:
        </>
      );
    }

    return (
      <>
        Пересадка на остановке<br />
        «{stationName}»:
      </>
    );
  };

  const getNoTransfersMessage = () => {
    return selectedLanguageRight === "ru"
      ? "Нет доступных пересадок"
      : selectedLanguageRight === "en"
      ? "No transfers available"
      : "没有可用的中转";
  };

  return (
    <div
      style={{
        transition: "0.5s ease-in-out",
        transform: isOpen ? "translateY(-100%)" : "translateY(100%)",
      }}
      className="transfer-widget"
    >
      <div className="transferLabel">
        {getTransferLabel()}
        {currentTransferData != null &&
        !Object.values(currentTransferData).every((value) => value === "") ? (
          <>
            <div>
              {currentTransferData?.metro_red?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={metroRedIcon}
                    alt="Metro Red Icon"
                  />
                  {currentTransferData.metro_red}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.metro_green?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={metroGreenIcon}
                    alt="Metro Green Icon"
                  />
                  {currentTransferData.metro_green}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.metro_blue?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={metroBlueIcon}
                    alt="Metro Blue Icon"
                  />
                  {currentTransferData.metro_blue}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.metro_orange?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={metroOrangeIcon}
                    alt="Metro Orange Icon"
                  />
                  {currentTransferData.metro_orange}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.metro_purple?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={metroPurpleIcon}
                    alt="Metro Purple Icon"
                  />
                  {currentTransferData.metro_purple}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.tram?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={tramIcon}
                    alt="Tram Icon"
                  />
                  {currentTransferData.tram}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.trolleybus?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={trolleyIcon}
                    alt="Trolleybus Icon"
                  />
                  {currentTransferData.trolleybus}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.bus?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={busIcon}
                    alt="Bus Icon"
                  />
                  {currentTransferData.bus}
                </div>
              ) : (
                ""
              )}
            </div>
            <div>
              {currentTransferData?.train?.length > 0 ? (
                <div className="transfer-line">
                  <img
                    style={{
                      width: "24px",
                      height: "24px",
                      marginRight: "8px",
                    }}
                    src={trainIcon}
                    alt="Train Icon"
                  />
                  {currentTransferData.train}
                </div>
              ) : (
                ""
              )}
            </div>
          </>
        ) : (
          <div className="transfers-body">{getNoTransfersMessage()}</div>
        )}
      </div>
    </div>
  );
});

export default TransferWidget;
