import React, { useEffect, useRef, useState } from "react";
import { createStackNavigator } from "@react-navigation/stack";
import { useWindowDimensions, Platform } from "react-native";
import Constants from "expo-constants";

import { Dimensions, StatusBar } from "react-native";

import { SheetManager } from "react-native-actions-sheet";
import { AS } from "@/storageControl";
import TrainBase from "@/components/trainbaseview";
import HowTo from "@/howto";
import { Menu } from "@/menu";
import News from "@/components/news";
import Setting from "@/components/Settings/settings";
import { useFavoriteStation } from "@/stateBox/useFavoriteStation";
import { optionData } from "@/lib/stackOption";
import AllTrainDiagramView from "@/components/AllTrainDiagramView";
import { useNavigation } from "@react-navigation/native";
import { news } from "@/config/newsUpdate";
import { useBottomTabBarHeight } from "@react-navigation/bottom-tabs";
import GeneralWebView from "@/GeneralWebView";
import { StationDiagramView } from "@/components/StationDiagram/StationDiagramView";
const Stack = createStackNavigator();

export function MenuPage() {
  const { favoriteStation, setFavoriteStation } = useFavoriteStation();
  const { height, width } = useWindowDimensions();
  const tabBarHeight = useBottomTabBarHeight();
  const navigation = useNavigation();
  const { addListener } = navigation;
  useEffect(() => {
    AS.getItem("startPage")
      .then((res) => {
        if (res == "true") navigation.navigate("positions");
      })
      .catch((e) => {
        //6.0以降false
        AS.setItem("startPage", "false");
      });

    //ニュース表示
    AS.getItem("status")
      .then((d) => {
        if (d != news) navigation.navigate("topMenu", { screen: "news" });
      })
      .catch(() => navigation.navigate("topMenu", { screen: "news" }));
    AS.getItem("isSetIcon")
      .then((isSetIcon) => {
        if (isSetIcon == "true") SheetManager.show("TrainIconUpdate");
      })
      .catch((error) => console.error("Error fetching icon setting:", error));
  }, []);

  const scrollRef = useRef(null);
  const [mapMode, setMapMode] = useState(false);
  const [mapHeight, setMapHeight] = useState(0);
  useEffect(() => {
    const MapHeight =
      height -
      tabBarHeight +
      (Platform.OS == "android" ? Constants.statusBarHeight : 0) -
      100 -
      ((((width / 100) * 80) / 20) * 9 + 10 + 30);
    setMapHeight(MapHeight);
  }, [height, tabBarHeight, width]);
  const [MapFullHeight, setMapFullHeight] = useState(0);
  useEffect(() => {
    const MapFullHeight =
      height -
      tabBarHeight +
      (Platform.OS == "android" ? Constants.statusBarHeight : 0);
    setMapFullHeight(MapFullHeight);
  }, [height, tabBarHeight, width]);
  useEffect(() => {
    const unsubscribe = addListener("tabPress", (e) => {
      scrollRef.current.scrollTo({
        y: mapHeight - 80,
        animated: true,
      });
      setMapMode(false);
      AS.getItem("favoriteStation")
        .then((d) => {
          const returnData = JSON.parse(d);
          if (favoriteStation.toString() != d) {
            setFavoriteStation(returnData);
          }
        })
        .catch((error) => {
          if (__DEV__) {
            console.warn("お気に入り駅の読み込みに失敗しました:", error);
          }
        });
    });

    return unsubscribe;
  }, [navigation, mapHeight, favoriteStation, setFavoriteStation]);
  return (
    <Stack.Navigator id={null}>
      <Stack.Screen
        name="menu"
        options={{
          headerShown: false,
          gestureEnabled: true,
          headerTransparent: true,
        }}
        children={() => (
          <Menu
            scrollRef={scrollRef}
            mapHeight={mapHeight}
            MapFullHeight={MapFullHeight}
            mapMode={mapMode}
            setMapMode={setMapMode}
          />
        )}
      />
      <Stack.Screen
        name="stDiagram"
        options={{ ...optionData, gestureEnabled: false }}
        component={StationDiagramView}
      />
      <Stack.Screen name="news" options={optionData} component={News} />
      <Stack.Screen
        name="setting"
        options={{
          ...optionData,
          gestureEnabled: false,
          cardOverlayEnabled: true,
        }}
        component={Setting}
      />
      <Stack.Screen
        name="trainbase"
        options={{ ...optionData }}
        component={TrainBase}
      />
      <Stack.Screen
        name="AllTrainIDList"
        options={{ ...optionData, gestureEnabled: false }}
        component={AllTrainDiagramView}
      />
      <Stack.Screen name="howto" options={optionData} component={HowTo} />
      <Stack.Screen
        name="generalWebView"
        options={optionData}
        component={GeneralWebView}
      />
    </Stack.Navigator>
  );
}
