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 { useTrainMenu } from "@/stateBox/useTrainMenu";
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";

import { FC, useEffect, useState } from "react";
import { LayoutAnimation, Text, TouchableOpacity, View } from "react-native";
import { SheetManager } from "react-native-actions-sheet";

type props = {
  stationID: string;
  displaySize: number;
  setDisplaySize: (size: number) => void;
};

export const FixedStation: FC<props> = ({
  stationID,
  displaySize,
  setDisplaySize,
}) => {
  const { mapSwitch } = useTrainMenu();
  const { currentTrain, setFixedPosition } = useCurrentTrain();
  const { getStationDataFromId } = useStationList();
  const { navigate } = useNavigation();
  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 { 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 (
    <View
      style={{ display: "flex", flexDirection: "column", flex: 1 }}
      pointerEvents="box-none"
    >
      <TouchableOpacity
        style={{
          flex: 1,
          flexDirection: "row",
          borderBottomColor: lineColor,
          borderBottomWidth: 2,
          position: "relative",
        }}
        activeOpacity={1}
        onPress={() => {
          const payload = {
            currentStation: station,
            navigate,
            goTo: "menu",
            onExit: () => SheetManager.hide("StationDetailView"),
          };
          //@ts-ignore
          SheetManager.show("StationDetailView", { payload });
        }}
      >
        <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",
              height: 22,
              overflow: "hidden",
              paddingLeft: 5,
            }}
          >
            <StationNumberMaker
              currentStation={station}
              singleSize={18}
              useEach={true}
            />
            <Text
              style={{
                fontSize: 14,
                textAlignVertical: "center",
                margin: 0,
                padding: 0,
                paddingLeft: 5,
                flex: 1,
                color: "white",
              }}
            >
              {station[0]?.Station_JP}
            </Text>
            <View
              style={{
                backgroundColor: "white",
                width: 6,
                borderLeftColor: lineColor,
                borderTopColor: lineColor,
                borderBottomColor: "white",
                borderRightColor: "white",
                borderBottomWidth: 18,
                borderLeftWidth: 10,
                borderRightWidth: 0,
                borderTopWidth: 5,
                height: 20,
              }}
            />
          </View>
          <View
            style={{
              height: "100%",
              backgroundColor: "white",
              flex: 1,
            }}
          >
            <Text style={{ fontSize: 18 }}>次の発車予定：</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]}
                displaySize={displaySize}
                key={d.train + "-fixedStationBox"}
              />
            ))
          ) : (
            <View style={{ backgroundColor: "white", flex: 1 }}>
              <Text style={{ fontSize: parseInt("11%") }}>
                当駅を発着する走行中の列車はありません。
              </Text>
            </View>
          )}
        </View>
      </TouchableOpacity>
      <View
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
          borderTopColor: lineColor,
          borderTopWidth: 2,
        }}
        pointerEvents="box-none"
      >
        <TouchableOpacity
          style={{
            flexDirection: "row",
            alignItems: "center",
          }}
          onPress={() => {
            setFixedPosition({ type: null, value: null });
          }}
        >
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              backgroundColor: lineColor,
              paddingHorizontal: 5,
              height: 26,
            }}
          >
            <Ionicons name="lock-closed" size={15} color="white" />
            <Text
              style={{
                color: "white",
                fontSize: 15,
                paddingRight: 5,
              }}
            >
              駅位置ロック中
            </Text>
            <Ionicons name="close" size={15} color="white" />
          </View>

          <View
            style={{
              backgroundColor: "#0000",
              width: 6,
              borderLeftColor: lineColor,
              borderTopColor: lineColor,
              borderBottomColor: "#0000",
              borderRightColor: "#0000",
              borderBottomWidth: 26,
              borderLeftWidth: 10,
              borderRightWidth: 0,
              borderTopWidth: 0,
              height: 26,
            }}
          />
        </TouchableOpacity>
        <TouchableOpacity
          style={{
            flexDirection: "row",
            alignItems: "center",
          }}
          onPress={() => {
            LayoutAnimation.configureNext({
              duration: 500,
              update: { type: "spring", springDamping: 0.7 },
            });
            if (displaySize === 226) {
              setDisplaySize(mapSwitch == "true" ? 76 : 80);
            } else {
              setDisplaySize(226);
            }
          }}
        >
          <View
            style={{
              backgroundColor: "#0000",
              width: 6,
              borderLeftColor: "#0000",
              borderTopColor: lineColor,
              borderBottomColor: "#0000",
              borderRightColor: lineColor,
              borderBottomWidth: 26,
              borderLeftWidth: 0,
              borderRightWidth: 10,
              borderTopWidth: 0,
              height: 26,
            }}
          />
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              backgroundColor: lineColor,
              paddingHorizontal: 5,
              height: 26,
            }}
            pointerEvents="none"
          >
            <Ionicons
              name={displaySize == 226 ? "chevron-up" : "chevron-down"}
              size={15}
              color="white"
            />
            <Text
              style={{
                color: "white",
                paddingRight: 5,
                backgroundColor: lineColor,
                fontSize: 15,
              }}
            >
              {displaySize == 226 ? "時刻表を縮小する" : "時刻表を展開する"}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const FixedStationBoxEachTrain = ({ d, station, displaySize }) => {
  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: displaySize == 226 ? "7.5%" : "33%",
        overflow: "visible",
      }}
    >
      <Text style={{ fontSize: parseInt("11%"), flex: 3 }}>{d.time}</Text>
      <Text style={{ fontSize: parseInt("11%"), flex: 4, color }}>{name}</Text>
      <Text style={{ fontSize: parseInt("11%"), flex: 4 }}>
        {d.lastStation}行
      </Text>
      <Text style={{ fontSize: parseInt("11%"), flex: 3 }}>
        {trainDelayStatus}
      </Text>
    </View>
  );
};
