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 { TouchableLayout } from "../TouchableLayout";

const SightTransferItem = ({ name, style, onPointerUp }) => {
  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 shouldAnimateValue = textWidth > containerWidth;
        setShouldAnimate(shouldAnimateValue);
        if (shouldAnimateValue) {
          containerRef.current.style.setProperty("--container-width", `${containerWidth}px`);
        }
      }
    };
    checkWidth();
    window.addEventListener("resize", checkWidth);
    return () => window.removeEventListener("resize", checkWidth);
  }, [name]);

  return (
    <div
      ref={containerRef}
      className="side-menu-sight-transfer pointer"
      style={style}
      onPointerUp={onPointerUp}
    >
      <span ref={textRef} className={shouldAnimate ? "marquee-text" : ""}>
        {name}
      </span>
    </div>
  );
};

const StationItem = ({
  station,
  handlePointerDown,
  handlePointerUp,
  handleStationClick,
  selectedStationId,
  selectedLanguage,
  stationSightsCache,
  sightArticles,
  sightArticlesEn,
  sightArticlesZh,
  onSightClick,
}) => {
  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; // 110% от ширины контейнера
        const shouldAnimateValue = textWidth > threshold;
        setShouldAnimate(shouldAnimateValue);

        // Устанавливаем CSS переменную для анимации
        if (shouldAnimateValue && containerRef.current) {
          containerRef.current.style.setProperty(
            "--container-width",
            `${containerWidth}px`,
          );
        }
      }
    };

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

  const cacheKey = `${station.id}_${selectedLanguage}`;
  const sights = stationSightsCache.get(cacheKey) || [];

  const getSightName = (sight) => {
    if (sight.short_name) {
      return sight.short_name;
    }

    if (!sight.left_article) {
      return sight.name;
    }

    const leftArticleData =
      selectedLanguage === "ru"
        ? sightArticles.get(sight.left_article + "_ru")
        : selectedLanguage === "en"
          ? sightArticlesEn.get(sight.left_article + "_en")
          : sightArticlesZh.get(sight.left_article + "_zh");

    return leftArticleData?.heading || sight.name;
  };

  return (
    <div>
      <div
        ref={containerRef}
        className="side-menu-sight"
        onPointerDown={(e) => handlePointerDown(e, station.id)}
        onPointerUp={(e) => {
          // Если у станции нет достопримечательностей, не открываем список
          if (sights.length > 0) {
            handlePointerUp(e, station.id, () =>
              handleStationClick(station.id),
            );
          }
        }}
      >
        <span ref={textRef} className={shouldAnimate ? "marquee-text" : ""}>
          {station.name}
        </span>
      </div>
      <div
        className={`side-menu-sight-transfer-list ${
          selectedStationId === station.id ? "open" : ""
        }`}
      >
        {sights.length > 0 ? (
          sights.map((sight, index) => (
            <SightTransferItem
              key={sight.id}
              name={getSightName(sight)}
              style={{
                borderBottom:
                  index < sights.length - 1
                    ? "1px solid rgba(255, 255, 255, 0.2)"
                    : "none",
                paddingBottom: index < sights.length - 1 ? "8px" : "6px",
                marginBottom: index < sights.length - 1 ? "4px" : "0",
              }}
              onPointerUp={(e) => {
                e.stopPropagation();
                if (onSightClick) {
                  const elementRect = e.currentTarget.getBoundingClientRect();
                  onSightClick(sight.id, elementRect.top);
                }
              }}
            />
          ))
        ) : (
          <div className="side-menu-sight-transfer-empty">
            {selectedLanguage === "ru"
              ? "Нет достопримечательностей"
              : selectedLanguage === "zh"
                ? "没有景点"
                : "No sights"}
          </div>
        )}
      </div>
    </div>
  );
};

const StationsList = observer(
  forwardRef(
    (
      {
        style,
        className,
        onCloseStation,
        isOpen,
        onStationSelected,
        onSightClick,
        setWeatherVisible,
      },
      ref,
    ) => {
      const containerRef = useRef(null);
      const store = useGeolocationStore();
      const {
        contextData,
        isLoading: isGeolocationLoading,
        selectedLanguage,
        isLeftWidgetOpen,
        setIsLeftWidgetOpen,
      } = store;
      const [stationList, setStationList] = useState([]);
      const [error, setError] = useState(null);
      const [isStationListLoading, setIsStationListLoading] = useState(true);
      const [selectedStationId, setSelectedStationId] = useState(null);

      useLayoutEffect(() => {
        if (containerRef.current) {
          if (className === "slide-in") {
            // Применяем стили для slide-in
            requestAnimationFrame(() => {
              if (containerRef.current) {
                containerRef.current.style.transform = "translateY(0)";
                containerRef.current.style.opacity = "1";
              }
            });
          } else if (className === "slide-out") {
            // Очищаем inline стили, чтобы CSS transition работал
            containerRef.current.style.transform = "";
            // Принудительно применяем reflow для запуска transition
            void containerRef.current.offsetHeight;
          }
        }
      }, [className]);
      const {
        routeStations,
        routeStationsEn,
        routeStationsZh,
        stationSightsCache,
        sightArticles,
        sightArticlesEn,
        sightArticlesZh,
      } = apiStore;

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

      useEffect(() => {
        async function fetchStationList() {
          setIsStationListLoading(true);
          setError(null);
          try {
            const response =
              selectedLanguage === "ru"
                ? routeStations
                : selectedLanguage === "en"
                  ? routeStationsEn
                  : routeStationsZh;

            // Сортировка по умолчанию по возрастанию (не зависит от sortingBy)
            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();
      }, [
        contextData?.routeId,
        isGeolocationLoading,
        selectedLanguage,
        routeStations,
        routeStationsEn,
        routeStationsZh,
      ]);

      const handleStationClick = (stationId) => {
        const newSelectedId =
          selectedStationId === stationId ? null : stationId;
        setSelectedStationId(newSelectedId);

        // Если остановка выбрана, вызываем callback для открытия списка достопримечательностей
        if (newSelectedId !== null && onStationSelected) {
          onStationSelected(newSelectedId);
        }
      };

      const handleClose = () => {
        setIsLeftWidgetOpen(false);
        setWeatherVisible(true);
        onCloseStation();
      };

      return (
        <div
          ref={containerRef}
          style={style}
          className={`side-menu-sights ${className || ""}`}
        >
          <div
            className="side-menu-sights-title"
            onPointerUp={() => {
              handleClose();
            }}
          >
            <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>
          <TouchableLayout className="side-menu-sights-block" ref={ref}>
            {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) => (
                <StationItem
                  key={station.id}
                  station={station}
                  handlePointerDown={handlePointerDown}
                  handlePointerUp={handlePointerUp}
                  handleStationClick={handleStationClick}
                  selectedStationId={selectedStationId}
                  selectedLanguage={selectedLanguage}
                  stationSightsCache={stationSightsCache}
                  sightArticles={sightArticles}
                  sightArticlesEn={sightArticlesEn}
                  sightArticlesZh={sightArticlesZh}
                  onSightClick={onSightClick}
                />
              ))
            )}
          </TouchableLayout>
        </div>
      );
    },
  ),
);

export default StationsList;
