import React, {
  useState,
  useEffect,
  useRef,
  useCallback,
  useMemo,
} from "react";
import { observer } from "mobx-react-lite";
import "../styles/ListOfSights.css";
import { useGeolocationStore, useColorStore } from "../stores";
import ContentAPI from "../api/content/content.api";
import { getMediaType } from "../utils/getMediaType";

// Импортируем новые компоненты
import SightFrame from "./ListOfSights/SightFrame";
import ListHeader from "./ListOfSights/ListHeader";
import SightsList from "./ListOfSights/SightsList";
import AlphabetNavigator from "./ListOfSights/AlphabetNavigator";
import LanguageSelector from "./ListOfSights/LanguageSelector";
import TransferWidget from "./ListOfSights/TransferWidget";
import { apiStore } from "../api/ApiStore/store";

const LANGUAGES = {
  EN: "en",
  RU: "ru",
  ZH: "zh",
};

const ListOfSights = observer(() => {
  const [sightData, setSightData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  const store = useGeolocationStore();
  const colorStore = useColorStore();
  const { currentColor, startColorAnimation } = colorStore;
  const { routeSights, routeSightsEn, routeSightsZh } = apiStore;
  const {
    nearestSightId,
    selectedSightId,
    setSelectedSightId,
    selectedLanguage,
    selectedLanguageRight,
    setSelectedLanguageRight,
    nearestStationId,
    isInteractingWith3D,
    isManualSelection,
    setIsManualSelection,
    isRightWidgetSelectorOpen,
    setIsRightWidgetSelectorOpen,
    isLeftWidgetOpen,
    isTransferWidgetOpen,
    setIsTransferWidgetOpen,
  } = store;
  const { context: contextData, routeStations } = apiStore;

  const [isLangMenuOpen, setIsLangMenuOpen] = useState(false);
  const [selectedLetter, setSelectedLetter] = useState(null);
  const [TransferWidgetData, setTransferWidgetData] = useState(null);
  const [isTransferButtonVisible, setIsTransferButtonVisible] = useState(false);
  const [showTransferButton, setShowTransferButton] = useState(false);
  const [highlightedSights, setHighlightedSights] = useState(new Set());
  const [isAlphabetDisabled, setIsAlphabetDisabled] = useState(false);

  const sightRefs = useRef({});
  const sightsListRef = useRef(null);
  const alphabetRef = useRef(null);
  const isInitialSelectionDone = useRef(false);

  const handleIconClick = () => {
    setIsRightWidgetSelectorOpen(!isRightWidgetSelectorOpen);
  };

  const handleSightClick = useCallback(
    (id) => {
      setSelectedSightId(String(id));
      setIsManualSelection(true);
      setIsRightWidgetSelectorOpen(false);
      // Закрываем виджет губернатора при выборе достопримечательности
      store.closeGovernorModal();
    },
    [setSelectedSightId, setIsRightWidgetSelectorOpen, store],
  );

  const handleLetterClick = (letter) => {
    // Если алфавит заблокирован, игнорируем клик
    if (isAlphabetDisabled) return;

    setSelectedLetter((prevLetter) => {
      const newLetter = prevLetter === letter ? null : letter;

      if (newLetter && sightData) {
        // Блокируем алфавит на время анимации
        setIsAlphabetDisabled(true);

        // Находим все достопримечательности, начинающиеся с выбранной буквы
        const sightsForLetter = sightData.filter((sight) => {
          if (!sight.name) return false;

          let sightFirstChar = sight.name.trim().charAt(0);

          // Для китайского языка используем пиньинь или иероглиф
          if (selectedLanguageRight === "zh") {
            if (sight.name_pinyin) {
              sightFirstChar = sight.name_pinyin.trim().toUpperCase().charAt(0);
            } else {
              // Если пиньинь нет, используем первый иероглиф
              sightFirstChar = sight.name.trim().charAt(0);
            }
          } else {
            sightFirstChar = sightFirstChar.toUpperCase();
          }

          return sightFirstChar === newLetter;
        });

        const sightIds = new Set(sightsForLetter.map((sight) => sight.id));

        // Скроллим к первой достопримечательности
        const firstSightForLetter = sightsForLetter[0];
        if (firstSightForLetter && sightRefs.current[firstSightForLetter.id]) {
          const targetElement = sightRefs.current[firstSightForLetter.id];

          if (targetElement) {
            // Используем setTimeout для гарантии, что OverlayScrollbars инициализирован
            setTimeout(() => {
              try {
                // Используем scrollIntoView, чтобы scroll-margin-top из CSS работал правильно
                targetElement.scrollIntoView({
                  behavior: "smooth",
                  block: "start",
                });

                // Fallback mechanism if scrollIntoView fails or is intercepted
                setTimeout(() => {
                  if (sightsListRef.current) {
                    const container = sightsListRef.current;
                    const rect = targetElement.getBoundingClientRect();
                    const containerRect = container.getBoundingClientRect();

                    // Check if element is visible in container
                    const isVisible =
                      rect.top >= containerRect.top &&
                      rect.bottom <= containerRect.bottom;

                    if (!isVisible && container.scrollTo) {
                      // Calculate relative position
                      const relativeTop = targetElement.offsetTop;
                      container.scrollTo({
                        top: relativeTop - 15,
                        behavior: "smooth",
                      });
                    }
                  }
                }, 100);
              } catch (error) {
                console.error("Ошибка при скролле к элементу:", error);
              }
            }, 100);

            // Запускаем анимацию после завершения скролла (примерно 500-600ms для smooth scroll)
            setTimeout(() => {
              setHighlightedSights(sightIds);

              // Через 1.5 секунды убираем подсветку и разблокируем алфавит
              setTimeout(() => {
                setHighlightedSights(new Set());
                setIsAlphabetDisabled(false);
              }, 1500);
            }, 600);
          }
        } else {
          setIsAlphabetDisabled(false);
        }
      } else {
        // Если буква отменена, убираем подсветку
        setHighlightedSights(new Set());
      }
      return newLetter;
    });
  };

  const handleLanguageChange = (val) => {
    setIsLangMenuOpen(false);
    setSelectedLanguageRight(val);
  };

  const handleTransferToggle = () => {
    setIsTransferWidgetOpen(!isTransferWidgetOpen);
  };

  const handleBackToNearest = useCallback(() => {
    setIsManualSelection(false);
    const sightData =
      selectedLanguageRight === "ru"
        ? routeSights
        : selectedLanguageRight === "en"
          ? routeSightsEn
          : routeSightsZh;

    if (sightData && sightData.length > 0) {
      const nearestSightInList = sightData.find((s) => s.id == nearestSightId);
      if (nearestSightInList) {
        setSelectedSightId(String(nearestSightInList.id));
      } else {
        setSelectedSightId(String(sightData[0].id));
      }
    } else {
      setSelectedSightId(null);
    }
    setIsRightWidgetSelectorOpen(false);
    // Закрываем виджет губернатора при возврате к ближайшей достопримечательности
    store.closeGovernorModal();
  }, [
    setSelectedSightId,
    routeSights,
    routeSightsEn,
    routeSightsZh,
    nearestSightId,
    selectedLanguageRight,
    setIsRightWidgetSelectorOpen,
    store,
  ]);

  // Запуск анимации цвета при монтировании компонента
  useEffect(() => {
    startColorAnimation();
  }, [startColorAnimation]);

  // Загрузка достопримечательностей
  useEffect(() => {
    setError(null);
    setIsLoading(true);

    const fetchSights = async () => {
      try {
        const sights =
          selectedLanguageRight === "ru"
            ? routeSights
            : selectedLanguageRight === "en"
              ? routeSightsEn
              : routeSightsZh;

        const processedSights = sights.map((sight) => ({
          ...sight,
          preview_media_type: getMediaType(sight.preview_media_type_raw),
          thumbnail_type: getMediaType(sight.thumbnail_type_raw),
        }));

        const sortedSights = [...processedSights].sort((a, b) => {
          if (a.name && b.name) {
            return a.name.localeCompare(b.name, selectedLanguageRight, {
              sensitivity: "base",
            });
          }
          return 0;
        });

        setSightData(sortedSights);
      } catch (err) {
        console.error("Ошибка загрузки достопримечательностей:", err);
        setError(
          "Не удалось загрузить достопримечательности. Пожалуйста, попробуйте позже.",
        );
        setSightData([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchSights();
  }, [contextData?.routeId, selectedLanguageRight]);

  // Анимация кнопки пересадок при открытии/закрытии левого меню
  useEffect(() => {
    if (isLeftWidgetOpen) {
      // При открытии левого меню - сначала показываем кнопку пересадок
      setIsTransferButtonVisible(true);
    } else {
      // При закрытии левого меню - сначала скрываем кнопку пересадок
      setIsTransferButtonVisible(false);
    }
  }, [isLeftWidgetOpen]);

  // Логика выбора достопримечательности
  useEffect(() => {
    if (!isLoading && sightData && sightData.length > 0) {
      if (!isInitialSelectionDone.current && !isManualSelection) {
        const nearestSightInList = sightData.find(
          (s) => s.id == nearestSightId,
        );
        if (nearestSightInList) {
          setSelectedSightId(String(nearestSightInList.id));
        } else {
          setSelectedSightId(String(sightData[0].id));
        }
        isInitialSelectionDone.current = true;
      } else if (!isInitialSelectionDone.current && isManualSelection) {
        const nearestSightInList = sightData.find(
          (s) => s.id == nearestSightId,
        );
        if (
          isManualSelection &&
          nearestSightInList &&
          nearestSightInList.id === selectedSightId
        ) {
          // Все ОК, продолжаем использовать выбранную вручную, если она совпадает с ближайшей
        } else if (isManualSelection && selectedSightId) {
          // Ничего не делаем здесь, выбранная вручную достопримечательность уже установлена.
        } else {
          if (nearestSightInList) {
            setSelectedSightId(String(nearestSightInList.id));
          } else {
            setSelectedSightId(String(sightData[0].id));
          }
        }
        isInitialSelectionDone.current = true;
        setIsManualSelection(false);
      }

      if (
        nearestSightId &&
        selectedSightId !== nearestSightId &&
        !isManualSelection &&
        !isInteractingWith3D
      ) {
        const newNearestSight = sightData.find((s) => s.id == nearestSightId);
        if (newNearestSight) {
          setSelectedSightId(String(newNearestSight.id));
        }
      }
    } else if (
      !isLoading &&
      (!sightData || sightData.length === 0) &&
      isInitialSelectionDone.current
    ) {
      setSelectedSightId(null);
      isInitialSelectionDone.current = false;
      setIsManualSelection(false);
    }
  }, [
    isLoading,
    sightData,
    nearestSightId,
    setSelectedSightId,
    selectedSightId,
    isManualSelection,
    isInteractingWith3D,
  ]);

  // Загрузка данных о пересадках для ближайшей станции
  useEffect(() => {
    if (!isLoading && nearestStationId != null) {
      const fetchTransferWidgetData = async () => {
        try {
          const station = routeStations.find((s) => s.id == nearestStationId);
          const response = station.transfers;

          setTransferWidgetData(response);
        } catch (err) {
          console.error("Ошибка в получении пересадок:", err);
          setTransferWidgetData(null);
        }
      };
      fetchTransferWidgetData();
    } else if (!isLoading && (!contextData?.routeId || !nearestStationId)) {
      setTransferWidgetData(null);
    }
  }, [isLoading, contextData?.routeId, nearestStationId, routeStations]);

  const currentSelectedSight = sightData
    ? sightData.find((sight) => sight.id == selectedSightId)
    : null;

  const sightFrameMedia = useMemo(() => {
    if (!currentSelectedSight) return null;

    // Если preview_media это строка (URL), используем её как path
    if (typeof currentSelectedSight.preview_media === "string") {
      return {
        id: currentSelectedSight.preview_media,
        path: currentSelectedSight.preview_media,
        media_type: currentSelectedSight.preview_media_type || null,
        type: currentSelectedSight.preview_media_type || null,
      };
    }

    if (
      typeof currentSelectedSight.preview_media === "object" &&
      currentSelectedSight.preview_media
    ) {
      return {
        id:
          currentSelectedSight.preview_media.id ||
          currentSelectedSight.preview_media,
        path:
          currentSelectedSight.preview_media.path ||
          currentSelectedSight.preview_media.url,
        media_type:
          currentSelectedSight.preview_media.type ||
          currentSelectedSight.preview_media.media_type,
        type:
          currentSelectedSight.preview_media.type ||
          currentSelectedSight.preview_media.media_type,
      };
    }

    return {
      id: currentSelectedSight.preview_media,
    };
  }, [currentSelectedSight]);

  return (
    <div className="right-widget">
      {currentSelectedSight && (
        <SightFrame
          key={currentSelectedSight.id}
          media={sightFrameMedia}
          sight_id={currentSelectedSight.id}
          sight_name={currentSelectedSight.name}
          selectedLanguageRight={selectedLanguageRight}
        />
      )}

      <div
        className={`list-of-sights ${
          isRightWidgetSelectorOpen ? "is-open" : ""
        }`}
      >
        <ListHeader
          isOpen={isRightWidgetSelectorOpen}
          onIconClick={handleIconClick}
          selectedLanguageRight={selectedLanguageRight}
          isManualSelection={isManualSelection}
          selectedSightId={selectedSightId}
          nearestSightId={nearestSightId}
          onTransferToggle={handleTransferToggle}
          isTransferWidgetOpen={isTransferWidgetOpen}
          onBackToNearest={handleBackToNearest}
          isLangOpen={isLangMenuOpen}
        />

        <TransferWidget
          isOpen={isTransferWidgetOpen}
          selectedLanguageRight={selectedLanguage}
        />

        <LanguageSelector
          selectedLanguageRight={selectedLanguageRight}
          onLanguageChange={handleLanguageChange}
          isOpen={isLangMenuOpen}
          onToggle={() => setIsLangMenuOpen(true)}
          onBackToNearest={handleBackToNearest}
        />

        <div className="sights-line"></div>

        <div className="alphabet-position">
          <SightsList
            isOpen={isRightWidgetSelectorOpen}
            isLoading={isLoading}
            error={error}
            sightData={sightData}
            onSightClick={handleSightClick}
            sightRefs={sightRefs}
            sightsListRef={sightsListRef}
            highlightedSights={highlightedSights}
          />

          <AlphabetNavigator
            ref={alphabetRef}
            selectedLetter={selectedLetter}
            onLetterClick={handleLetterClick}
            sightData={sightData}
            selectedLanguage={selectedLanguageRight}
            isDisabled={isAlphabetDisabled}
          />
        </div>

        <div
          className="transfer-button-container"
          style={{
            transition: "transform 0.3s ease",
          }}
        >
          <div
            style={{
              backgroundColor: "black",
              width: "48px",
              height: "48px",
              borderRadius: "50%",
            }}
            className="transfer-button"
          >
            <svg
              onPointerUp={handleTransferToggle}
              xmlns="http://www.w3.org/2000/svg"
              width="48"
              height="48"
              viewBox="0 0 48 48"
              className="icon-color-animated"
              fill="none"
              style={{
                cursor: "pointer",
                "--animated-color": currentColor,
              }}
            >
              <path
                d="M24.0013 0C23.3513 0 22.7013 0.03 22.0413 0.08C10.4213 1 1.01127 10.41 0.0812683 22.03C-0.428732 28.39 1.55127 34.28 5.14127 38.83C5.60127 39.42 5.76127 40.21 5.46127 40.89C4.76127 42.43 3.63127 43.64 3.05127 44.23C2.50127 44.78 1.97127 45.27 1.38127 45.7C0.791268 46.13 0.841268 47.03 1.45127 47.42C2.08127 47.82 3.01127 47.99 4.12127 47.99C6.84127 47.99 10.5813 46.99 13.3013 46.06C13.5013 45.99 13.7013 45.96 13.9113 45.96C14.1813 45.96 14.4613 46.02 14.7113 46.13C17.5713 47.33 20.7113 48 24.0013 48C24.6513 48 25.3213 47.97 25.9813 47.92C37.6313 46.98 47.0613 37.51 47.9313 25.85C48.9913 11.76 37.8713 0 24.0013 0ZM29.5113 37.71C29.4813 37.82 29.3413 37.94 29.2313 37.98C27.7413 38.48 26.2713 39.12 24.7313 39.42C22.9513 39.77 21.1413 39.68 19.5513 38.58C18.2213 37.66 17.7313 36.36 17.8113 34.8C17.9013 32.91 18.5113 31.13 19.0013 29.33C19.5213 27.42 20.1113 25.53 20.4613 23.59C20.9413 20.94 19.7813 20.48 17.3913 20.74C16.8013 20.8 16.2313 21.04 15.5813 21.22C15.7213 20.62 15.8313 20.08 15.9913 19.55C16.0213 19.45 19.6313 17.94 21.4413 17.78C23.3513 17.61 25.2013 17.8 26.6013 19.32C27.3913 20.17 27.6113 21.21 27.5913 22.33C27.5413 24.8 26.5813 27.07 25.9813 29.42C25.6113 30.86 25.2513 32.3 24.9313 33.75C24.8413 34.15 24.8413 34.59 24.8813 35C24.9613 35.97 25.4413 36.39 26.4313 36.57C27.6213 36.78 28.7213 36.45 29.9313 36.04C29.7813 36.66 29.6613 37.19 29.5213 37.7L29.5113 37.71ZM26.8513 15.21C26.6513 15.23 26.4613 15.23 26.2013 15.25C24.4013 15.27 22.7313 14.15 22.2013 12.52C21.5913 10.65 22.5613 8.71 24.5313 7.86C26.7913 6.88 29.5813 8.07 30.2713 10.33C31.0513 12.87 29.0613 14.95 26.8613 15.21H26.8513Z"
                fill="white"
              />
            </svg>
          </div>
        </div>
      </div>
    </div>
  );
});

export default ListOfSights;
