import React, { useEffect, useRef, useState } from "react";
import {
  View,
  Platform,
  ToastAndroid,
  Text,
  TouchableOpacity,
} from "react-native";
import { WebView } from "react-native-webview";
import Constants from "expo-constants";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { AS } from "./storageControl";
import { news } from "./config/newsUpdate";
import { getStationList, lineList } from "./lib/getStationList";
import { StationDeteilView } from "./components/ActionSheetComponents/StationDeteilView";
import { injectJavascriptData } from "./lib/webViewInjectjavascript";
import { getStationList2 } from "./lib/getStationList2";
/* 
import StatusbarDetect from './StatusbarDetect';
var Status = StatusbarDetect(); */

export default function Apps({ navigation, webview }) {
  const { navigate } = navigation;
  var urlcache = "";

  //画面表示関連
  const [iconSetting, setIconSetting] = useState(undefined);
  const [mapSwitch, setMapSwitch] = useState(undefined);
  const [stationMenu, setStationMenu] = useState(undefined);

  //駅情報画面用
  const StationBoardAcSR = useRef(null);
  const [stationBoardData, setStationBoardData] = useState(undefined);
  const [originalStationList, setOriginalStationList] = useState();
  const [selectedStation, setSelectedStation] = useState(undefined);
  useEffect(() => {
    getStationList().then(setOriginalStationList);
  }, []);

  //地図表示テキスト
  const injectJavascript = injectJavascriptData(
    mapSwitch,
    iconSetting,
    stationMenu
  );

  useEffect(() => {
    //ニュース表示
    AS.getItem("status")
      .then((d) => {
        if (d != news) navigate("news");
      })
      .catch((e) => navigate("news"));
  }, []);

  useEffect(() => {
    //列車アイコンスイッチ
    AS.getItem("iconSwitch")
      .then((d) => {
        if (d) {
          setIconSetting(d);
        } else {
          AS.setItem("iconSwitch", "true").then(Updates.reloadAsync);
        }
      })
      .catch((d) => AS.setItem("iconSwitch", "true").then(Updates.reloadAsync));
  }, []);

  useEffect(() => {
    //地図スイッチ
    AS.getItem("mapSwitch")
      .then((d) => {
        if (d) {
          setMapSwitch(d);
        } else {
          AS.setItem("mapSwitch", "false").then(Updates.reloadAsync);
        }
      })
      .catch((d) => AS.setItem("mapSwitch", "false").then(Updates.reloadAsync));
  }, []);

  useEffect(() => {
    //駅メニュースイッチ
    AS.getItem("stationSwitch")
      .then((d) => {
        if (d) {
          setStationMenu(d);
        } else {
          AS.setItem("stationSwitch", "true").then(Updates.reloadAsync);
        }
      })
      .catch((d) =>
        AS.setItem("stationSwitch", "true").then(Updates.reloadAsync)
      );
  }, []);

  const onMessage = (event) => {
    if (!event.nativeEvent.data.includes("PopUpMenu")) {
      navigate("trainbase", { info: event.nativeEvent.data, from: "Train" });
      return;
    }
    if (!originalStationList) {
      alert("駅名標データを取得中...");
      return;
    }
    const selectedStationPDFAddress = event.nativeEvent.data
      .split(",")[3]
      .replace("'", "")
      .replace("'", "");

    const findStationEachLine = (selectLine) => {
      let NearStation = selectLine.filter(
        (d) => d.StationTimeTable == selectedStationPDFAddress
      );
      return NearStation;
    };

    let returnDataBase = lineList
      .map((d) => findStationEachLine(originalStationList[d]))
      .filter((d) => d.length > 0)
      .reduce((pre, current) => {
        pre.push(...current);
        return pre;
      }, []);
    if (returnDataBase.length) {
      setStationBoardData(returnDataBase);
      StationBoardAcSR.current?.setModalVisible();
    } else {
      setStationBoardData(undefined);
      StationBoardAcSR.current?.hide();
    }

    return;
  };

  const onNavigationStateChange = (event) => {
    if (event.url != urlcache) {
      //URL二重判定回避
      urlcache = event.url;

      if (event.url.includes("https://train.jr-shikoku.co.jp/usage.htm")) {
        if (Platform.OS === "android") navigate("howto");
        webview?.current.goBack();
        //Actions.howto();
      } else if (
        event.url.includes("https://train.jr-shikoku.co.jp/train.html")
      ) {
        //Actions.trainbase({info: event.url});
        if (Platform.OS === "android")
          navigate("trainbase", { info: event.url });
        webview?.current.goBack();
      }
    }
  };

  return (
    <View
      style={{
        height: "100%",
        paddingTop: Platform.OS == "ios" ? Constants.statusBarHeight : 0,
      }}
    >
      {/* {Status} */}
      <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
        onNavigationStateChange={onNavigationStateChange}
        onMessage={onMessage}
        injectedJavaScript={injectJavascript}
        onTouchMove={() => StationBoardAcSR.current?.hide()}
      />
      <MapsButton
        onPress={() => navigate("trainMenu", { webview })}
        top={Platform.OS == "ios" ? Constants.statusBarHeight : 0}
        mapSwitch={mapSwitch == "true" ? "flex" : "none"}
      />
      <ReloadButton
        onPress={() => webview.current.reload()}
        top={Platform.OS == "ios" ? Constants.statusBarHeight : 0}
      />

      <StationDeteilView
        StationBoardAcSR={StationBoardAcSR}
        currentStation={stationBoardData}
        originalStationList={originalStationList}
      />
    </View>
  );
}

const MapsButton = ({ onPress, top, mapSwitch }) => {
  const styles = {
    touch: {
      position: "absolute",
      top,
      left: 10,
      width: 50,
      height: 50,
      backgroundColor: "#0099CC",
      borderColor: "white",
      borderStyle: "solid",
      borderWidth: 1,
      borderRadius: 50,
      alignContent: "center",
      alignSelf: "center",
      alignItems: "center",
      display: mapSwitch,
    },
    text: {
      textAlign: "center",
      width: "auto",
      height: "auto",
      textAlignVertical: "center",
      fontWeight: "bold",
      color: "white",
    },
  };
  return (
    <TouchableOpacity onPress={onPress} style={styles.touch}>
      <View style={{ flex: 1 }} />
      <Text style={styles.text}>三</Text>
      <View style={{ flex: 1 }} />
    </TouchableOpacity>
  );
};

const ReloadButton = ({ onPress, top, mapSwitch }) => {
  const styles = {
    touch: {
      position: "absolute",
      top,
      right: 10,
      width: 50,
      height: 50,
      backgroundColor: "#0099CC",
      borderColor: "white",
      borderStyle: "solid",
      borderWidth: 1,
      borderRadius: 50,
      alignContent: "center",
      alignSelf: "center",
      alignItems: "center",
      display: mapSwitch,
    },
    text: {
      textAlign: "center",
      width: "auto",
      height: "auto",
      textAlignVertical: "center",
      fontWeight: "bold",
      color: "white",
    },
  };
  return (
    <TouchableOpacity onPress={onPress} style={styles.touch}>
      <View style={{ flex: 1 }} />
      <Ionicons name="reload" color="white" size={30} />
      <View style={{ flex: 1 }} />
    </TouchableOpacity>
  );
};
