import lineColorList from "@/assets/originData/lineColorList";
import { StationNumberMaker } from "@/components/駅名表/StationNumberMaker";
import { checkDuplicateTrainData } from "@/lib/checkDuplicateTrainData";
import {
  CustomTrainData,
  eachTrainDiagramType,
  StationProps,
} from "@/lib/CommonTypes";
import { getCurrentTrainData } from "@/lib/getCurrentTrainData";
import { getTrainDelayStatus } from "@/lib/getTrainDelayStatus";
import { getTrainType } from "@/lib/getTrainType";
import { objectIsEmpty } from "@/lib/objectIsEmpty";
import { getTime, trainTimeFiltering } from "@/lib/trainTimeFiltering";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { useAreaInfo } from "@/stateBox/useAreaInfo";
import { useCurrentTrain } from "@/stateBox/useCurrentTrain";
import { useStationList } from "@/stateBox/useStationList";

import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { Text, TouchableOpacity, View } from "react-native";

export const FixedStation = ({ stationID }) => {
  const { currentTrain, setFixedPosition } = useCurrentTrain();
  const { getStationDataFromId } = useStationList();
  const [station, setStation] = useState<StationProps[]>([]);
  useEffect(() => {
    const data = getStationDataFromId(stationID);
    setStation(data);
  }, [stationID]);
  const lineColor =
    station.length > 0
      ? lineColorList[station[0]?.StationNumber.slice(0, 1)]
      : "white";
  ////

  const { allTrainDiagram } = useAllTrainDiagram();
  const { areaInfo, areaStationID } = useAreaInfo();
  const [stationDiagram, setStationDiagram] = useState({}); //当該駅の全時刻表
  const [isInfoArea, setIsInfoArea] = useState(false);

  useEffect(() => {
    // 現在の駅に停車するダイヤを作成する副作用[列車ダイヤと現在駅情報]
    if (!allTrainDiagram) {
      setStationDiagram({});
      return;
    }
    if (station.length == 0) {
      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]);

  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) => !d.isThrough)
      .filter((d) => d.lastStation != station[0].Station_JP); //最終列車表示設定
    setSelectedTrain(data);
  }, [trainTimeAndNumber, currentTrain /*finalSwitch*/]);

  return (
    <TouchableOpacity
      style={{ flex: 1, flexDirection: "row" }}
      onPress={() => {
        setFixedPosition({ type: null, value: null });
      }}
    >
      <View
        style={{
          flex: 3,
          flexDirection: "column",
          alignContent: "center",
          alignSelf: "center",
          alignItems: "center",
          height: "100%",
          backgroundColor: "white",
        }}
      >
        <View
          style={{
            backgroundColor: lineColor,
            flexDirection: "row",
            width: "100%",
            alignContent: "center",
            alignItems: "center",
          }}
        >
          <StationNumberMaker
            currentStation={station}
            singleSize={18}
            useEach={true}
          />
          <Text
            style={{
              fontSize: 18,
              textAlignVertical: "center",
              margin: 0,
              padding: 0,
              flex: 1,
              color: "white",
            }}
          >
            {station[0]?.Station_JP}
          </Text>
          <View
            style={{
              backgroundColor: "white",
              width: 10,
              borderLeftColor: lineColor,
              borderTopColor: lineColor,
              borderBottomColor: "white",
              borderBottomWidth: 16,
              borderLeftWidth: 8,
              borderRightWidth: 0,
              borderTopWidth: 5,
              height: "100%",
            }}
          />
        </View>
        <View
          style={{
            height: "100%",
            backgroundColor: "white",
            flex: 1,
          }}
        >
          <Text style={{ fontSize: 20 }}>次の発車予定：</Text>
        </View>
      </View>

      <View
        style={{
          flex: 5,
          flexDirection: "column",
          backgroundColor: "white",
          borderTopWidth: 5,
          borderTopColor: lineColor,
          overflow: "hidden",
        }}
      >
        {selectedTrain.length > 0 ? (
          selectedTrain.map((d) => (
            <FixedStationBoxEachTrain
              d={d}
              station={station[0]}
              key={d.train + "-fixedStationBox"}
            />
          ))
        ) : (
          <View style={{ backgroundColor: "white", flex: 1 }}>
            <Text style={{ fontSize: 20 }}>
              当駅を発着する走行中の列車はありません。
            </Text>
          </View>
        )}
      </View>
    </TouchableOpacity>
  );
};

const FixedStationBoxEachTrain = ({ d, station }) => {
  const { currentTrain } = useCurrentTrain();
  const { stationList } = useStationList();
  const { allCustomTrainData } = useAllTrainDiagram();
  const currentTrainData = checkDuplicateTrainData(
    currentTrain.filter((a) => a.num == d.train),
    stationList
  );

  const trainDelayStatus = `${getTrainDelayStatus(
    currentTrainData,
    station.Station_JP
  )}`;
  const [train, setTrain] = useState<CustomTrainData>(
    getCurrentTrainData(d.train, currentTrain, allCustomTrainData)
  );
  useEffect(() => {
    setTrain(getCurrentTrainData(d.train, currentTrain, allCustomTrainData));
  }, [currentTrain, d.train]);
  const { name, color } = getTrainType({ type: train.type, whiteMode: true });
  return (
    <View
      style={{
        backgroundColor: "white",
        flexDirection: "row",
        height: "33%",
        overflow: "visible",
      }}
    >
      <Text style={{ fontSize: 14, flex: 3 }}>{d.time}</Text>
      <Text style={{ fontSize: 14, flex: 4, color }}>{name}</Text>
      <Text style={{ fontSize: 14, flex: 4 }}>{d.lastStation}行</Text>
      <Text style={{ fontSize: 14, flex: 3 }}>{trainDelayStatus}</Text>
    </View>
  );
};
