import React, { useState, useEffect } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { Switch } from "react-native-elements";
import { widthPercentageToDP as wp } from "react-native-responsive-screen";
import LottieView from "lottie-react-native";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { customTrainDataDetector } from "../custom-train-data";
import { useInterval } from "../../lib/useInterval";
import trainList from "../../assets/originData/trainList";
import { objectIsEmpty } from "../../lib/objectIsEmpty";

let diagramData = undefined;

/**
 *
 * 1-30M しおかぜ
 * 31-58D 南風
 * 1001-1030M いしづち(併結)
 * 1041-1046M いしづち(単独)
 * 1051-1082D 宇和海
 * 1091M MX松山
 * 1092M MX高松
 * 2001-2010D しまんと
 * 2071-2086D あしずり
 * 3001-3033D うずしお
 * 3101-3177M マリンライナー
 * 4001-4011D 剣山
 * 5006,13,22,29 うずしお(岡山直通南風併結)
 * 5831-5843D 土佐くろしお鉄道ごめん・なはり線直通快速
 * 5853-5892D 土佐くろしお鉄道ごめん・なはり線直通普通
 * 8011,8012D 四国まんなか千年ものがたり
 * 8031,(8041) サンライズ瀬戸, 琴平(延長)
 * 8053,8054D トキの夜明けのものがたり
 * 8176,8179D アンパントロッコタカマツ
 * 8277,8278D アンパントロッココトヒラ
 * 8451,8452D よしの川トロッコ
 * 8814,8819D しまんトロッコ
 * 8911-8914D 伊予灘ものがたり
 * 9001-9030* いしづち(リレー)
 * 9031M サンライズ瀬戸琴平(延長)(臨時？)
 * 9062D 四国まんなか千年ものがたり(臨時？)
 */
export default function LED_vision(props) {
  const HeaderConfig = {
    headers: {
      referer: "https://train.jr-shikoku.co.jp/sp.html",
    },
  };
  const [trainDiagram, setTrainDiagram] = useState(null); // 全列車のダイヤを列番ベースで整理
  const [stationDiagram, setStationDiagram] = useState({}); //当該駅の全時刻表
  const [currentTrain, setCurrentTrain] = useState(null); //現在在線中の全列車
  const [currentTrainLoading, setCurrentTrainLoading] = useState("loading");
  const [finalSwitch, setFinalSwitch] = useState(false);
  const [trainIDSwitch, setTrainIDSwitch] = useState(false);
  const [trainDescriptionSwitch, setTrainDescriptionSwitch] = useState(false);

  const parseAllTrainDiagram = (text) => {
    const val = text.replace("[\r\n", "").split(",\r\n");
    let trainDiagram = {};
    val.forEach((element) => {
      try {
        let data = JSON.parse(element);
        Object.keys(data).forEach((key) => (trainDiagram[key] = data[key]));
      } catch (e) {}
    });
    return trainDiagram;
  };

  useEffect(() => {
    //全列車リストを生成する副作用[無条件初回実行]
    fetch(
      "https://train.jr-shikoku.co.jp/g?arg1=station&arg2=traintimeinfo&arg3=dia",
      HeaderConfig
    )
      .then((response) => response.text())
      .then((d) => {
        if (d.indexOf("<title>404 Not Found</title>") != -1) throw Error;
        setTrainDiagram(parseAllTrainDiagram(d));
      })
      .catch((d) => {
        console.log("fallback");
        setTrainDiagram(trainList);
      });
  }, []);

  useEffect(() => {
    // 現在の駅に停車するダイヤを作成する副作用[列車ダイヤと現在駅情報]
    if (!trainDiagram) {
      setStationDiagram({});
      return;
    }
    let returnData = {};
    Object.keys(trainDiagram).forEach((key) => {
      if (trainDiagram[key].match(props.station.Station_JP + ",")) {
        returnData[key] = trainDiagram[key];
      }
    });
    setStationDiagram(returnData);
  }, [trainDiagram, props.station]);

  const getCurrentTrain = () =>
    fetch(
      "https://train.jr-shikoku.co.jp/g?arg1=train&arg2=train",
      HeaderConfig
    )
      .then((response) => response.json())
      .then((d) =>
        d.map((x) => ({ num: x.TrainNum, delay: x.delay, Pos: x.Pos }))
      )
      .then((d) => {
        setCurrentTrain(d);
        setCurrentTrainLoading("success");
      })
      .catch((e) => {
        console.log("えらー");
        setCurrentTrainLoading("error");
      });

  useEffect(getCurrentTrain, []); //初回だけ現在の全在線列車取得

  useInterval(getCurrentTrain, 15000); //15秒毎に全在線列車取得

  const getTime = (stationDiagram, station) => {
    const returnData = Object.keys(stationDiagram).map((d) => {
      let a = {};
      stationDiagram[d].split("#").forEach((data) => {
        if (data.match("着")) {
          a.lastStation = data.split(",着,")[0];
        }
        if (data.split(",")[0] === station.Station_JP) {
          if (data.match(",発,")) {
            a.time = data.split(",発,")[1];
          } else {
            a.time = data.split(",着,")[1];
            a.lastStation = "当駅止";
          }
        }
      });
      return { train: d, time: a.time, lastStation: a.lastStation };
    });
    return returnData.sort((a, b) => {
      switch (true) {
        case parseInt(a.time.split(":")[0]) < parseInt(b.time.split(":")[0]):
          return -1;
        case parseInt(a.time.split(":")[0]) > parseInt(b.time.split(":")[0]):
          return 1;
        case parseInt(a.time.split(":")[1]) < parseInt(b.time.split(":")[1]):
          return -1;
        case parseInt(a.time.split(":")[1]) > parseInt(b.time.split(":")[1]):
          return 1;
      }
    });
  };

  const [trainTimeAndNumber, setTrainTimeAndNumber] = useState(null);

  useEffect(() => {
    //現在の駅に停車する列車から時刻を切り出してLEDベースにフォーマット
    if (objectIsEmpty(stationDiagram)) return () => {};
    const getTimeData = getTime(stationDiagram, props.station);
    setTrainTimeAndNumber(getTimeData);
  }, [stationDiagram]);

  const timeFiltering = (d) => {
    const date = new Date();
    const newDate = new Date();
    let data = d.time.split(":");
    let delay = isNaN(currentTrain.filter((t) => t.num == d.train)[0].delay)
      ? 0
      : currentTrain.filter((t) => t.num == d.train)[0].delay;

    date.setHours(parseInt(data[0]));
    date.setMinutes(parseInt(data[1]) + parseInt(delay));
    if (!(newDate > date)) {
      return true;
    }

    return false;
  };

  const [selectedTrain, setSelectedTrain] = useState([]);
  useEffect(() => {
    if (!trainTimeAndNumber) return () => {};
    if (!currentTrain) return () => {};
    const data = trainTimeAndNumber
      .filter((d) => currentTrain.map((m) => m.num).includes(d.train))
      .filter(timeFiltering)
      .filter((d) => !!finalSwitch || d.lastStation != "当駅止");
    setSelectedTrain(data);
  }, [trainTimeAndNumber, currentTrain, finalSwitch]);
  return (
    <View
      style={{
        width: wp("98%"),
        /*  height: wp("98%")/10*9, */ backgroundColor: "#432",
        borderWidth: 1,
        margin: 10,
        marginHorizontal: wp("1%"),
      }}
    >
      <Header
        currentTrainLoading={currentTrainLoading}
        setCurrentTrainLoading={setCurrentTrainLoading}
        getCurrentTrain={getCurrentTrain}
      />
      {selectedTrain.map((d, index) => (
        <EachData
          d={d}
          trainIDSwitch={trainIDSwitch}
          trainDescriptionSwitch={trainDescriptionSwitch}
          props={props}
          currentTrain={currentTrain}
          customTrainDataDetector={customTrainDataDetector}
          navigate={props.navigate}
        />
      ))}
      <Footer
        trainIDSwitch={trainIDSwitch}
        setTrainIDSwitch={setTrainIDSwitch}
        trainDescriptionSwitch={trainDescriptionSwitch}
        setTrainDescriptionSwitch={setTrainDescriptionSwitch}
        finalSwitch={finalSwitch}
        setFinalSwitch={setFinalSwitch}
      />
    </View>
  );
}
const Header = ({
  currentTrainLoading,
  setCurrentTrainLoading,
  getCurrentTrain,
}) => (
  <View
    style={{
      alignContent: "center",
      alignItems: "center",
      width: "100%",
      marginVertical: 10,
      flexDirection: "row",
    }}
  >
    <View style={{ flex: 1 }}></View>
    <View style={{}}>
      <Text style={{ fontSize: 25, color: "white", fontWeight: "bold" }}>
        次の列車
      </Text>
      <Text style={{ fontSize: 15, color: "white" }}>Next Train</Text>
    </View>
    <View style={{ flex: 1, flexDirection: "row-reverse" }}>
      {currentTrainLoading == "loading" ? (
        <LottieView
          autoPlay
          loop
          style={{ width: 40, height: 40, marginRight: 30 }}
          source={require("../../assets/51690-loading-diamonds.json")}
        />
      ) : currentTrainLoading == "error" ? (
        <Ionicons
          name="reload"
          color="white"
          size={30}
          style={{ marginRight: 30 }}
          onPress={() => {
            setCurrentTrainLoading("loading");
            getCurrentTrain();
          }}
        />
      ) : null}
    </View>
  </View>
);

const Footer = ({
  trainIDSwitch,
  setTrainIDSwitch,
  trainDescriptionSwitch,
  setTrainDescriptionSwitch,
  finalSwitch,
  setFinalSwitch,
}) => {
  return (
    <View style={{ flexDirection: "row", padding: 10, alignItems: "center" }}>
      <Text
        style={{
          alignItems: "center",
          alignContent: "center",
          textAlign: "center",
          textAlignVertical: "center",
          color: "white",
        }}
      >
        種別名 / 列番
      </Text>
      <Switch value={trainIDSwitch} onValueChange={setTrainIDSwitch} />
      <View style={{ flex: 1 }} />
      <Text
        style={{
          alignItems: "center",
          alignContent: "center",
          textAlign: "center",
          textAlignVertical: "center",
          color: "white",
        }}
      >
        列車情報
      </Text>
      <Switch
        value={trainDescriptionSwitch}
        onValueChange={setTrainDescriptionSwitch}
      />
      <View style={{ flex: 1 }} />
      <Text
        style={{
          alignItems: "center",
          alignContent: "center",
          textAlign: "center",
          textAlignVertical: "center",
          color: "white",
        }}
      >
        当駅止表示
      </Text>
      <Switch value={finalSwitch} onValueChange={setFinalSwitch} />
    </View>
  );
};

const EachData = ({
  d,
  trainIDSwitch,
  trainDescriptionSwitch,
  props,
  currentTrain,
  customTrainDataDetector,
  navigate,
}) => {
  const getTrainType = (data) => {
    switch (data) {
      case "Rapid":
        return { color: "aqua", name: "快速" };
      case "LTDEXP":
        return { color: "red", name: "特急" };
      case "NightLTDEXP":
        return { color: "red", name: "寝台特急" };
      case "Normal":
        return { color: "white", name: "普通列車" };
    }
  };
  const [train, setTrain] = useState(customTrainDataDetector(d.train));
  useEffect(() => {
    setTrain(customTrainDataDetector(d.train));
  }, [currentTrain, d.train, trainDescriptionSwitch]);
  return (
    <>
      <TouchableOpacity
        style={{
          alignContent: "center",
          alignItems: "center",
          width: "94%",
          marginVertical: 5,
          marginHorizontal: "3%",
          backgroundColor: "#000",
          flexDirection: "row",
        }}
        onPress={() => {
          if (train.type != "Normal") {
            navigate("trainbase", {
              info: "train.html?tn=" + d.train,
              from: "LED",
            });
          }
        }}
      >
        <TrainName
          train={train}
          trainIDSwitch={trainIDSwitch}
          d={d}
          getTrainType={getTrainType(train.type)}
        />
        <LastStation d={d} />
        <DependTime d={d} />
        <StatusAndDelay
          currentTrain={currentTrain}
          d={d}
          props={props}
          trainDescriptionSwitch={trainDescriptionSwitch}
        />
      </TouchableOpacity>
      {trainDescriptionSwitch && !!train.info && <Description train={train} />}
    </>
  );
};

const TrainName = ({ train, trainIDSwitch, d, getTrainType }) => {
  const { trainName, trainNumDistance } = train;
  let TrainNumber = "";
  if (trainNumDistance != undefined) {
    const timeInfo =
      parseInt(d.train.replace("M", "").replace("D", "")) - trainNumDistance;
    TrainNumber = timeInfo + "号";
  }
  return (
    <View style={{ flex: 9 }}>
      <Text
        style={{
          fontSize: trainName.length > 6 ? parseInt("13%") : parseInt("18%"),
          color: getTrainType.color,
          fontWeight: "bold",
        }}
      >
        {trainIDSwitch
          ? d.train
          : `${getTrainType.name} ${trainName}${TrainNumber}`}
      </Text>
    </View>
  );
};

const LastStation = ({ d }) => {
  return (
    <View style={{ flex: 4, flexDirection: "row" }}>
      <Text
        style={{
          fontSize:
            d.lastStation.length > 4 ? parseInt("13%") : parseInt("18%"),
          color: "white",
          fontWeight: "bold",
        }}
      >
        {d.lastStation}
      </Text>
    </View>
  );
};
const DependTime = ({ d }) => {
  return (
    <View style={{ flex: 3 }}>
      <Text
        style={{
          fontSize: parseInt("18%"),
          color: "white",
          fontWeight: "bold",
        }}
      >
        {d.time}
      </Text>
    </View>
  );
};

const checkDuplicateTrainData = (currentTrainArray) => {
  const notNyujoData = currentTrainArray.filter((d) => d.delay !== "入線");
  if (currentTrainArray.length == 1) return currentTrainArray[0];
  if (notNyujoData.length == 0) return currentTrainArray[0];
  else return notNyujoData[0];
};
const StatusAndDelay = ({ currentTrain, d, props, trainDescriptionSwitch }) => {
  const [status, setStatus] = useState("");
  useEffect(() => {
    const array = currentTrain.filter((a) => a.num == d.train);
    const current = checkDuplicateTrainData(array);
    // 土讃線複数存在対策
    if (!current) return () => {};
    const delay = current.delay;
    switch (true) {
      case delay === "入線":
        if (current.Pos === props.station.Station_JP) {
          setStatus("当駅始発");
          break;
        } else {
          setStatus("発車前");
          break;
        }
      case isNaN(delay):
        setStatus(delay);
        break;
      case delay === 0:
        setStatus("定刻通り");
        break;
      default:
        setStatus(delay + "分遅れ");
        break;
    }
  }, [currentTrain, d.train, trainDescriptionSwitch]);
  return (
    <View style={{ flex: 4 }}>
      <Text
        style={{
          fontSize: parseInt("18%"),
          color: "white",
          fontWeight: "bold",
          paddingLeft: 1,
        }}
      >
        {status}
      </Text>
    </View>
  );
};
const Description = ({ train }) => {
  return (
    <View
      style={{
        alignContent: "center",
        alignItems: "center",
        width: "94%",
        marginVertical: 5,
        marginHorizontal: "3%",
        backgroundColor: "#000",
        flexDirection: "row",
      }}
    >
      <View style={{ flex: 4 }}>
        <Text
          style={{
            fontSize: parseInt("18%"),
            color: "green",
            fontWeight: "bold",
          }}
        >
          {" "}
          &gt; {train.info}
        </Text>
      </View>
    </View>
  );
};
