import React, { useEffect, useRef, useState } from "react";
import { NavigationContainer } from "@react-navigation/native";
import {
  createStackNavigator,
  TransitionPresets,
} from "@react-navigation/stack";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { AntDesign, Ionicons } from "@expo/vector-icons";
import { Platform, UIManager } from "react-native";
import { UpdateAsync } from "./UpdateAsync.js";
import { getStationList2 } from "./lib/getStationList2";
import { AS } from "./storageControl";
import Apps from "./Apps";
import TNDView from "./ndView";
import TrainBase from "./trainbaseview";
import HowTo from "./howto";
import Menu from "./menu";
import News from "./components/news.js";
import Setting from "./components/settings.js";
import TrainMenu from "./components/trainMenu.js";
import FavoriteList from "./components/FavoriteList.js";
import { LogBox } from "react-native";

LogBox.ignoreLogs([
  "ViewPropTypes will be removed",
  "ColorPropType will be removed",
]);
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
if (Platform.OS === "android") {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}
export default function App() {
  useEffect(() => {
    UpdateAsync();
  }, []);
  const [favoriteStation, setFavoriteStation] = useState([]);

  useEffect(() => {
    AS.getItem("favoriteStation")
      .then((d) => {
        const returnData = JSON.parse(d);
        setFavoriteStation(returnData);
      })
      .catch((d) => console.log(d));
  }, []);
  const [busAndTrainData, setBusAndTrainData] = useState([]);
  useEffect(() => {
    AS.getItem("busAndTrain")
      .then((d) => {
        const returnData = JSON.parse(d);
        setBusAndTrainData(returnData);
      })
      .catch((d) => {
        fetch(
          "https://script.google.com/macros/s/AKfycbw0UW6ZeCDgUYFRP0zxpc_Oqfy-91dBdbWv-cM8n3narKp14IyCd2wy5HW7taXcW7E/exec"
        )
          .then((d) => d.json())
          .then((d) => {
            setBusAndTrainData(d);
            AS.setItem("busAndTrain", JSON.stringify(d));
          });
      });
  }, []);

  return (
    <NavigationContainer name="Root" style={{ flex: 1 }}>
      <Tab.Navigator detachInactiveScreens={false}>
        <Tab.Screen
          name="login"
          options={{
            tabBarLabel: "位置情報",
            headerTransparent: true,
            gestureEnabled: true,
            tabBarIcon: initIcon("barchart", "AntDesign"),
          }}
        >
          {(props) => (
            <Top
              {...props}
              favoriteStation={favoriteStation}
              setFavoriteStation={setFavoriteStation}
              busAndTrainData={busAndTrainData}
            />
          )}
        </Tab.Screen>
        <Tab.Screen
          name="menuPage"
          options={{
            tabBarLabel: "リンク",
            headerTransparent: true,
            gestureEnabled: true,
            tabBarIcon: initIcon("ios-radio", "Ionicons"),
          }}
        >
          {(props) => (
            <MenuPage
              {...props}
              favoriteStation={favoriteStation}
              setFavoriteStation={setFavoriteStation}
              busAndTrainData={busAndTrainData}
            />
          )}
        </Tab.Screen>
        <Tab.Screen
          name="home"
          options={{
            tabBarLabel: "運行情報",
            headerTransparent: true,
            gestureEnabled: true,
            tabBarIcon: initIcon("md-train", "Ionicons"),
          }}
        >
          {(props) => <TNDView {...props} />}
        </Tab.Screen>
      </Tab.Navigator>
    </NavigationContainer>
  );
}

const initIcon = (name, type) => {
  switch (type) {
    case "Ionicons":
      return ({ focused, color, size }) => (
        <Ionicons name={name} size={32} color={focused ? "#0099CC" : "black"} />
      );
    case "AntDesign":
      return ({ focused, color, size }) => (
        <AntDesign
          name={name}
          size={32}
          color={focused ? "#0099CC" : "black"}
        />
      );
  }
};

const Top = ({
  navigation,
  favoriteStation,
  setFavoriteStation,
  busAndTrainData,
}) => {
  const webview = useRef();

  //地図用
  const [mapsStationData, setMapsStationData] = useState(undefined);

  useEffect(() => {
    getStationList2().then(setMapsStationData);
  }, []);

  useEffect(() => {
    const unsubscribe = navigation.addListener("tabLongPress", (e) => {
      navigation.navigate("favoriteList");
    });

    return unsubscribe;
  }, [navigation]);

  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Apps"
        options={{
          headerShown: false,
          gestureEnabled: true,
          headerTransparent: true,
        }}
      >
        {(props) => (
          <Apps
            {...props}
            webview={webview}
            favoriteStation={favoriteStation}
            setFavoriteStation={setFavoriteStation}
            busAndTrainData={busAndTrainData}
          />
        )}
      </Stack.Screen>
      <Stack.Screen
        name="trainbase"
        options={{
          title: "トレインビジョン",
          gestureEnabled: true,
          ...TransitionPresets.SlideFromRightIOS,
        }}
      >
        {(props) => <TrainBase {...props} />}
      </Stack.Screen>
      <Stack.Screen
        name="howto"
        options={{
          title: "使い方",
          ...optionData,
        }}
      >
        {(props) => <HowTo {...props} />}
      </Stack.Screen>
      <Stack.Screen name="news" options={optionData}>
        {(props) => <News {...props} />}
      </Stack.Screen>
      <Stack.Screen name="trainMenu" options={optionData}>
        {(props) => (
          <TrainMenu
            {...props}
            webview={webview}
            stationData={mapsStationData}
          />
        )}
      </Stack.Screen>
      <Stack.Screen
        name="favoriteList"
        options={{ ...optionData, gestureEnabled: false }}
      >
        {(props) => (
          <FavoriteList
            {...props}
            webview={webview}
            stationData={mapsStationData}
            favoriteStation={favoriteStation}
            setFavoriteStation={setFavoriteStation}
          />
        )}
      </Stack.Screen>
    </Stack.Navigator>
  );
};
function MenuPage({
  navigation,
  favoriteStation,
  setFavoriteStation,
  busAndTrainData,
}) {
  useEffect(() => {
    const unsubscribe = navigation.addListener("tabPress", (e) => {
      AS.getItem("favoriteStation")
        .then((d) => {
          const returnData = JSON.parse(d);
          if (favoriteStation.toString() != d) {
            setFavoriteStation(returnData);
          }
        })
        .catch((d) => console.log(d));
    });

    return unsubscribe;
  }, [navigation]);
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="menu"
        options={{
          headerShown: false,
          gestureEnabled: true,
          headerTransparent: true,
        }}
      >
        {(props) => (
          <Menu
            {...props}
            favoriteStation={favoriteStation}
            setFavoriteStation={setFavoriteStation}
            busAndTrainData={busAndTrainData}
          />
        )}
      </Stack.Screen>
      <Stack.Screen name="setting" options={optionData}>
        {(props) => <Setting {...props} />}
      </Stack.Screen>
      <Stack.Screen
        name="trainbase"
        options={{
          ...TransitionPresets.ModalPresentationIOS,
          cardOverlayEnabled: true,
          headerShown: false,
          gestureEnabled: true,
          headerTransparent: true,
          gestureResponseDistance: { vertical: 300 },
        }}
      >
        {(props) => <TrainBase {...props} />}
      </Stack.Screen>
    </Stack.Navigator>
  );
}
const optionData = {
  gestureEnabled: true,
  ...TransitionPresets.ModalPresentationIOS,
  cardOverlayEnabled: true,
  headerTransparent: true,
  headerShown: false,
};
