import React, { useState, useEffect } from "react";
import { View, useWindowDimensions } from "react-native";
import dayjs from "dayjs";
import { useInterval } from "../../lib/useInterval";
import { objectIsEmpty } from "../../lib/objectIsEmpty";
import { useCurrentTrain } from "../../stateBox/useCurrentTrain";
import { useAreaInfo } from "../../stateBox/useAreaInfo";
import { AS } from "../../storageControl";
import { Footer } from "./LED_Vision_Component/Footer";
import { Header } from "./LED_Vision_Component/Header";
import { Description } from "./LED_inside_Component/Description";
import { EachData } from "./EachData";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { trainPosition } from "@/lib/trainPositionTextArray";
import { AreaDescription } from "./LED_inside_Component/AreaDescription";

/**
 *
 * 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 { station, navigate, openStationACFromEachTrainInfo } = props;
  const { currentTrain } = useCurrentTrain();
  const [stationDiagram, setStationDiagram] = useState({}); //当該駅の全時刻表
  const [finalSwitch, setFinalSwitch] = useState(false);
  const [trainIDSwitch, setTrainIDSwitch] = useState(false);
  const [trainDescriptionSwitch, setTrainDescriptionSwitch] = useState(false);
  const [isInfoArea, setIsInfoArea] = useState(false);
  const { areaInfo, areaStationID } = useAreaInfo();
  const { allTrainDiagram } = useAllTrainDiagram();

  useEffect(() => {
    AS.getItem("LEDSettings/trainIDSwitch").then((data) => {
      setTrainIDSwitch(data === "true");
    });
    AS.getItem("LEDSettings/trainDescriptionSwitch").then((data) => {
      setTrainDescriptionSwitch(data === "true");
    });
    AS.getItem("LEDSettings/finalSwitch").then((data) => {
      setFinalSwitch(data === "true");
    });
  }, []);

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

  /*
{lastStation: "当駅止", time: "12:34", train: "1234M"}
  */
  const [trainTimeAndNumber, setTrainTimeAndNumber] = useState([]);

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

  const [selectedTrain, setSelectedTrain] = useState([]);
  useEffect(() => {
    if (!trainTimeAndNumber) return () => {};
    if (!currentTrain) return () => {};
    const data = trainTimeAndNumber
      .filter((d) => currentTrain.map((m) => m.num).includes(d.train)) //現在の列車に絞る[ToDo]
      .filter(timeFiltering)
      .filter((d) => !!finalSwitch || d.lastStation != station[0].Station_JP) //最終列車表示設定
    setSelectedTrain(data);
  }, [trainTimeAndNumber, currentTrain, finalSwitch]);

  const getTime = (stationDiagram, station) => {
    const returnData = Object.keys(stationDiagram)
      .map((trainNum) => {
        let trainData = {};
        stationDiagram[trainNum].split("#").forEach((data) => {
          if (data.match("着")) {
            trainData.lastStation = data.split(",着,")[0];
          }
          if (data.match("着編")) {
            trainData.lastStation = data.split(",着編,")[0];
          }
          if (data.split(",")[0] === station.Station_JP) {
            if (data.match(",発,")) {
              trainData.time = data.split(",発,")[1];
            }else if (data.match(",発編,")) {
              trainData.time = data.split(",発編,")[1];
            } else if (data.match(",通編,")) {
              trainData.time = data.split(",通編,")[1];
              trainData.isThrough = true;
            }  else if (data.match(",着,")) {
              trainData.time = data.split(",着,")[1];
            }else if (data.match(",着編,")) {
              trainData.time = data.split(",着編,")[1];
            }
          }
        });
        return {
          train: trainNum,
          time: trainData.time,
          lastStation: trainData.lastStation,
          isThrough: trainData.isThrough,
        };
      })
      .filter((d) => d.time);
    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;
        default:
          return 0;
      }
    });
  };

  const timeFiltering = (d) => {

    const baseTime = 2;
    if (currentTrain.filter((t) => t.num == d.train).length == 0) {
      const date = dayjs();
      const trainTime = date
        .hour(parseInt(d.time.split(":")[0]))
        .minute(parseInt(d.time.split(":")[1]));

      if (date.isAfter(trainTime)) {
        return false;
      } else if (trainTime.diff(date) < baseTime * 60 * 60 * 1000) {
        return true;
      }
      return false;
    } else {
      const Pos = trainPosition(
        currentTrain.filter((t) => t.num == d.train)[0]
      );
      const nextPos = Pos.isBetween ? Pos.Pos.to : Pos.Pos.Pos;
      const PrePos = Pos.isBetween ? Pos.Pos.from : "";
      if (station[0].Station_JP == nextPos) {
        if(d.lastStation != station[0].Station_JP) return true;
      } else if (station[0].Station_JP == PrePos) {
        return false;
      }
      const date = dayjs();
      let [h, m] = 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;
      const db = date.hour(parseInt(h)).minute(parseInt(m) + parseInt(delay));
      return !date.isAfter(db);
    }
  };
  const { width } = useWindowDimensions();
  const adjustedWidth = width * 0.98;
  return (
    <View
      style={{
        width: adjustedWidth,
        /*  height: wp("98%")/10*9, */ backgroundColor: "#432",
        borderWidth: 1,
        margin: 10,
        marginHorizontal: width * 0.01,
      }}
    >
      <Header station={station[0]} />
      {selectedTrain.map((d) => (
        <EachData
          {...{
            d,
            trainIDSwitch,
            trainDescriptionSwitch,
            navigate,
            openStationACFromEachTrainInfo,
          }}
          station={station[0]}
          key={d.train}
        />
      ))}
      {areaInfo != "" && isInfoArea && (
        <AreaDescription
          numberOfLines={1}
          areaInfo={areaInfo}
          onClick={() => alert(areaInfo)}
        />
      )}

      <Footer
        {...{
          trainIDSwitch,
          setTrainIDSwitch,
          trainDescriptionSwitch,
          setTrainDescriptionSwitch,
          finalSwitch,
          setFinalSwitch,
        }}
      />
    </View>
  );
}
