import lineColorList from "@/assets/originData/lineColorList";
import { getStationID } from "@/lib/eachTrainInfoCoreLib/getStationData";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { useCurrentTrain } from "@/stateBox/useCurrentTrain";
import { useStationList, StationProps } from "@/stateBox/useStationList";
import { useEffect, useState } from "react";
import { Text, TouchableOpacity, View, Image, Platform } from "react-native";
import { customTrainDataDetector } from "../custom-train-data";
import { getStringConfig, typeID } from "@/lib/getStringConfig";
import { getTrainType } from "@/lib/getTrainType";
import Constants from "expo-constants";

export const FixedPositionBox = () => {
  const { fixedPosition, setFixedPosition } = useCurrentTrain();

  return (
    <View
      style={{
        position: "absolute",
        top: Platform.OS == "ios" ? Constants.statusBarHeight : 0,
        borderRadius: 5,
        zIndex: 500,
        width: "100%",
        height: 50,
        flexDirection: "row",
      }}
    >
      <View style={{ width: 60 }} />
      {fixedPosition.type === "station" && (
        <FixedStation stationID={fixedPosition.value} />
      )}
      {fixedPosition.type === "train" && (
        <FixedTrain trainID={fixedPosition.value} />
      )}
      <View style={{ width: 60 }} />
    </View>
  );
};

export const FixedStation = ({ stationID }) => {
  const { fixedPosition, setFixedPosition } = useCurrentTrain();
  const { getStationDataFromId } = useStationList();
  const [station, setStation] = useState<StationProps[]>([]);
  useEffect(() => {
    const data = getStationDataFromId(stationID);
    setStation(data);
  }, [stationID]);
  console.log(station);
  const lineColor =
    station.length > 0
      ? lineColorList[station[0]?.StationNumber.slice(0, 1)]
      : "white";
  return (
    <TouchableOpacity
      style={{ flex: 1, flexDirection: "column" }}
      onPress={() => {
        setFixedPosition({ type: null, value: null });
      }}
    >
      <View style={{ flex: 1, flexDirection: "row" }}>
        <View
          style={{
            paddingHorizontal: 5,
            backgroundColor: lineColor,
            flexDirection: "row",
          }}
        >
          {station.map((s) => {
            if (s.StationNumber === null) return null;
            return (
              <View
                key={s.StationNumber}
                style={{
                  flexDirection: "column",
                  alignItems: "center",
                  borderColor: lineColor,
                  backgroundColor: "white",
                  borderWidth: 1,
                  borderRadius: 30,
                  width: 25,
                  height: 25,
                }}
              >
                <Text style={{ fontSize: 10, margin: 0, padding: 0 }}>
                  {s.StationNumber?.slice(0, 1)}
                </Text>
                <Text style={{ fontSize: 10, margin: 0, padding: 0 }}>
                  {s.StationNumber?.slice(1)}
                </Text>
              </View>
            );
          })}
        </View>
        <View
          style={{
            backgroundColor: lineColor,
          }}
        >
          <Text style={{ fontSize: 20 }}>{station[0]?.Station_JP}</Text>
        </View>
        <View
          style={{
            backgroundColor: lineColor,
            width: 10,
            borderLeftColor: lineColor,
            borderBottomColor: "white",
            borderBottomWidth: 25,
            borderLeftWidth: 10,
            borderRightWidth: 0,
            borderTopWidth: 0,
          }}
        ></View>
        <View style={{ backgroundColor: "white", flex: 1 }}>
          <Text style={{ fontSize: 20 }}>駅情報固定中</Text>
        </View>
      </View>

      <View
        style={{
          flex: 1,
          flexDirection: "row",
          backgroundColor: lineColor,
        }}
      >
        <View style={{ backgroundColor: "white", flex: 1 }}>
          <Text style={{ fontSize: 20 }}>次：15:00 快速マリン　岡山</Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};

export const FixedTrain = ({ trainID }) => {
  const { fixedPosition, setFixedPosition, currentTrain } = useCurrentTrain();
  const { allCustomTrainData, allTrainDiagram } = useAllTrainDiagram();

  const getTrainDataFromCurrentTrain = (trainNum: string) => {
    const customTrainData = customTrainDataDetector(
      trainNum,
      allCustomTrainData
    );
    switch (customTrainData.type) {
      case "Normal":
      case "OneMan":
        const currentTrainData = currentTrain.filter((a) => a.num == trainNum);
        if (currentTrainData.length == 0) return customTrainData;
        else if (currentTrainData[0].Type.includes("rapid:")) {
          const typeText = currentTrainData[0].Type.split(":");
          const returnData = {
            type: "Rapid",
            trainName: typeText[1].replace("\r", ""),
            trainIcon: null,
            trainNumDistance: null,
            info: "",
          };
          return returnData;
        }
        return customTrainData;
      default:
        return customTrainData;
    }
  };
  const [train, setTrain] = useState<{
    Index: string;
    num: string;
    delay: string;
    Pos: string;
    PosNum: string;
    Direction: number;
    Type: string;
    Line: string;
  }>(null);
  const [customData, setCustomData] = useState<{
    ToData: string;
    TrainNumber: string;
    id: string;
    img: string;
    isWanman: boolean;
    trainName: string;
    trainNumDistance: number;
    type: typeID;
    viaData: string;
    info?: string;
    uwasa?: string;
  }>(getTrainDataFromCurrentTrain(trainID));
  useEffect(() => {
    setCustomData(getTrainDataFromCurrentTrain(trainID));
  }, [currentTrain, trainID]);
  useEffect(() => {
    currentTrain.forEach((d) => {
      if (d.num == trainID) setTrain(d);
    });
  }, [trainID, currentTrain]);

  const [ToData, setToData] = useState("");
  useEffect(() => {
    if (customData.ToData && customData.ToData != "") {
      setToData(customData.ToData);
    } else {
      const base = allTrainDiagram[trainID];
      if (!base) return;
      const data = base.split("#");
      setToData(data[data.length - 2].split(",")[0]);
    }
  }, [customData, train]);
  const [stringConfig, setStringConfig] = useState([, ,]);
  useEffect(() => {
    const x = getStringConfig(customData.type, customData.TrainNumber);
    setStringConfig(x);
  }, [customData]);
  return (
    <TouchableOpacity
      style={{ flex: 1, flexDirection: "row" }}
      onPress={() => {
        setFixedPosition({ type: null, value: null });
      }}
    >
      <View style={{ flex: 1, flexDirection: "row" }}>
        <View
          style={{
            padding: 5,
            backgroundColor: getTrainType(customData.type).color,
            flexDirection: "row",
            alignContent: "center",
            alignSelf: "center",
            height: "100%",
          }}
        >
          <Image source={{ uri: customData.img }} width={30} height={35} />
          <View
            style={{
              flexDirection: "column",
              alignContent: "center",
              alignSelf: "center",
            }}
          >
            <Text
              style={{
                fontSize: 15,
                fontFamily: stringConfig[1] ? "JR-Nishi" : undefined,
                fontWeight: !stringConfig[1] ? "bold" : undefined,
              }}
            >
              {stringConfig[0]}
            </Text>
            <Text style={{ fontSize: 10 }}>{ToData}行</Text>
          </View>
        </View>
        <View
          style={{
            backgroundColor: getTrainType(customData.type).color,
            width: 10,
            borderLeftColor: getTrainType(customData.type).color,
            borderTopColor: "white",
            borderBottomColor: "white",
            borderTopWidth: 25,
            borderBottomWidth: 25,
            borderLeftWidth: 10,
            borderRightWidth: 0,
          }}
        ></View>
        <View style={{ backgroundColor: "white", flex: 1 }}>
          <Text style={{ fontSize: 20 }}>列車情報追跡中</Text>
          <Text style={{ fontSize: 20 }}>次は　どこですか</Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};
