import React from "react";
import { Platform, LayoutAnimation } from "react-native";
import { WebView } from "react-native-webview";

import { lineList } from "../../lib/getStationList";
import { checkDuplicateTrainData } from "../../lib/checkDuplicateTrainData";
import { useFavoriteStation } from "../../stateBox/useFavoriteStation";
import { useCurrentTrain } from "../../stateBox/useCurrentTrain";
import { useDeviceOrientationChange } from "../../stateBox/useDeviceOrientationChange";
import { SheetManager } from "react-native-actions-sheet";

import { useNavigation } from "@react-navigation/native";
import { useTrainMenu } from "../../stateBox/useTrainMenu";
import { stationNamePair } from "../../lib/getStationList2";
import { useStationList } from "../../stateBox/useStationList";
export const AppsWebView = ({ openStationACFromEachTrainInfo }) => {
  const { webview, currentTrain } = useCurrentTrain();
  const { navigate } = useNavigation();
  const { favoriteStation } = useFavoriteStation();
  const { isLandscape } = useDeviceOrientationChange();
  const { originalStationList } = useStationList();
  const {
    setSelectedLine,
    mapsStationData: stationData,
    setLoadError,
    setTrainInfo,
    injectJavascript,
  } = useTrainMenu();
  var urlcache = "";
  let once = false;

  const onNavigationStateChange = ({ url }) => {
    if (url == urlcache) return;
    //URL二重判定回避
    urlcache = url;
    switch (true) {
      case url.includes("https://train.jr-shikoku.co.jp/usage.htm"):
        if (Platform.OS === "android") navigate("howto", { info: url });
        webview?.current.goBack();
        //Actions.howto();
        break;
      case url.includes("https://train.jr-shikoku.co.jp/train.html"):
        //Actions.trainbase({info: url});
        if (Platform.OS === "android") navigate("trainbase", { info: url });
        webview?.current.goBack();
        break;
    }
  };

  const onMessage = (event) => {
    const { data } = event.nativeEvent;
    if (data.includes("train.html")) {
      navigate("trainbase", { info: data, from: "Train" });
      return;
    }
    if (!originalStationList) {
      alert("駅名標データを取得中...");
      return;
    }
    const dataSet = JSON.parse(data);
    switch (dataSet.type) {
      case "LoadError": {
        setLoadError(true);
        return;
      }
      case "PopUpMenu":
        {
          const findStationEachLine = (selectLine) =>
            selectLine.filter((d) => d.StationTimeTable == dataSet.pdf);
          let returnDataBase = lineList
            .map((d) => findStationEachLine(originalStationList[d]))
            .filter((d) => d.length > 0)
            .reduce((pre, current) => {
              pre.push(...current);
              return pre;
            }, []);

          if (returnDataBase.length) {
            const payload = {
              currentStation: returnDataBase,
              navigate: navigate,
              goTo: "Apps",
              useShow: () =>
                SheetManager.show("StationDetailView", { payload }),
              onExit: () => SheetManager.hide("StationDetailView"),
            };
            SheetManager.show("StationDetailView", { payload });
          }
        }
        return;
      case "ShowTrainTimeInfo": {
        const { trainNum, limited } = dataSet;
        //alert(trainNum, limited);
        LayoutAnimation.easeInEaseOut();
        setTrainInfo({
          trainNum,
          limited,
          trainData: checkDuplicateTrainData(
            currentTrain.filter((a) => a.num == trainNum)
          ),
        }); //遅延情報は未実装
        if (isLandscape) return;
        const payload = {
          data: { trainNum, limited },
          navigate,
          openStationACFromEachTrainInfo,
        };
        SheetManager.show("EachTrainInfo", { payload });
        return;
      }
      case "currentLines": {
        const lineInfo = dataSet.currentLines.split("\n")[0];
        const lineID = stationNamePair[lineInfo];

        setSelectedLine(lineID);
        return;
      }
      default: {
        return;
      }
    }
  };

  const onLoadEnd = () => {
    if (once) return () => {};
    if (!stationData) return () => {};
    if (favoriteStation.length < 1) return () => {};
    const getStationLine = (now) => {
      const returnData = Object.keys(stationData).filter((d) => {
        const cache = stationData[d].findIndex(
          (data) => data.Station_JP == now.Station_JP
        );
        return cache != -1;
      });
      return returnData[0];
    };
    const lineName = getStationLine(favoriteStation[0][0]);
    webview.current?.injectJavaScript(
      `MoveDisplayStation('${lineName}_${favoriteStation[0][0].MyStation}_${favoriteStation[0][0].Station_JP}')`
    );
    once = true;
  };

  return (
    <WebView
      useWebKit
      ref={webview}
      source={{ uri: "https://train.jr-shikoku.co.jp/sp.html" }}
      originWhitelist={[
        "https://train.jr-shikoku.co.jp",
        "https://train.jr-shikoku.co.jp/sp.html",
      ]}
      mixedContentMode={"compatibility"}
      javaScriptEnabled
      allowsBackForwardNavigationGestures
      setSupportMultipleWindows
      {...{ onMessage, onNavigationStateChange, onLoadEnd }}
      injectedJavaScript={injectJavascript}
    />
  );
};
