import React, { useState, useEffect, FC } from "react";
import { View, useWindowDimensions } from "react-native";
import { objectIsEmpty } from "@/lib/objectIsEmpty";
import { useCurrentTrain } from "@/stateBox/useCurrentTrain";
import { useAreaInfo } from "@/stateBox/useAreaInfo";
import { AS } from "@/storageControl";
import { Footer } from "@/components/発車時刻表/LED_Vision_Component/Footer";
import { Header } from "@/components/発車時刻表/LED_Vision_Component/Header";
import { EachData } from "@/components/発車時刻表/EachData";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { AreaDescription } from "@/components/発車時刻表/LED_inside_Component/AreaDescription";
import { getTime, trainTimeFiltering } from "@/lib/trainTimeFiltering";
import { eachTrainDiagramType, StationProps } from "@/lib/CommonTypes";
import { useNavigation } from "@react-navigation/native";

/**
 *
 * 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 四国まんなか千年ものがたり(臨時？)
 */
type props = {
  station: StationProps[];
};
export const LED_vision: FC<props> = (props) => {
  const { station } = props;

  const { navigate, addListener, isFocused } = useNavigation();
  const { currentTrain } = useCurrentTrain();
  const [stationDiagram, setStationDiagram] = useState<{
    [key: string]: string;
  }>({}); //当該駅の全時刻表
  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<
    eachTrainDiagramType[]
  >([]);

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

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

  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>
  );
};
