import { migrateTrainName } from "@/lib/eachTrainInfoCoreLib/migrateTrainName";
import { getStringConfig, typeID } from "@/lib/getStringConfig";
import { getTrainType } from "@/lib/getTrainType";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { FC, useEffect, useLayoutEffect, useMemo, useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  useWindowDimensions,
} from "react-native";
import { customTrainDataDetector } from "../custom-train-data";
import dayjs from "dayjs";
import { SheetManager } from "react-native-actions-sheet";
import { useNavigation } from "@react-navigation/native";
import { lineList } from "@/lib/getStationList";
import { useStationList } from "@/stateBox/useStationList";
import { SharedValue, useAnimatedStyle } from "react-native-reanimated";
import Animated from "react-native-reanimated";
import lineColorList from "@/assets/originData/lineColorList";

export const ExGridViewItem: FC<{
  d: {
    trainNumber: string;
    array: string;
    name: string;
    type: string;
    time: string;
    isOperating: boolean;
  };
  index: number;
  width: SharedValue<number>;
  array: {
    train: string;
    lastStation: string;
    time: string;
    isThrough?: boolean;
  }[];
}> = ({ d, index, width, array }) => {
  const { allCustomTrainData } = useAllTrainDiagram();
  const { originalStationList, stationList } = useStationList();
  const { navigate, goBack } = useNavigation();
  const [trainData, setTrainData] = useState<{
    ToData: string;
    TrainNumber: string;
    id: string;
    img: string;
    info?: string;
    infoUrl: string;
    infogram: string;
    isEdit: boolean;
    isSeason: boolean;
    trainName: string;
    trainNumDistance?: number;
    type: typeID;
    viaData?: string;
    uwasa?: string;
  }>();
  useEffect(() => {
    if (allCustomTrainData) {
      allCustomTrainData.forEach((x) => {
        if (x.TrainNumber === d.trainNumber) {
          setTrainData(x);
        }
      });
    }
  }, []);
  const { color, name, data } = getTrainType(trainData?.type, true);
  // 列車名、種別、フォントの取得
  const [
    typeString,
    trainName,
    fontAvailable,
    isOneMan,
    infogram,
    isEdit,
    uwasa,
    vehicleFormation,
    trainInfoUrl,
  ] = useMemo(() => {
    const {
      type,
      trainName,
      trainNumDistance,
      infogram,
      isEdit,
      uwasa,
      vehicleFormation,
      trainInfoUrl,
    } = customTrainDataDetector(d.trainNumber, allCustomTrainData);
    const [typeString, fontAvailable, isOneMan] = getStringConfig(
      type,
      d.trainNumber
    );
    const trainData = d.array.split("#").filter((d) => d !== "");
    switch (true) {
      case trainData[trainData.length - 1] === undefined:
        return [
          typeString,
          "",
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,
        ];
      default:
        // 行先がある場合は、行先を取得
        const trainName = (d.type == "着" || d.type == "着編") ? trainData[0].split(",")[0] : trainData[trainData.length - 1].split(",")[0]
        return [
          typeString,
          migrateTrainName(trainName),
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,
        ];
    }
  }, [d.array]);
  const timeArray = d.time.split(":").map((s) => parseInt(s));
  const formattedTime = dayjs()
    .set("hour", timeArray[0])
    .set("minute", timeArray[1])
    .format("m");
  let isSameTimeBefore = false;
  if (index > 0) {
    const beforeItem = array[index - 1];
    const beforeTimeArray = beforeItem.time.split(":").map((s) => parseInt(s));
    const beforeFormattedTime = dayjs()
      .set("hour", beforeTimeArray[0])
      .set("minute", beforeTimeArray[1])
      .format("m");
    isSameTimeBefore = beforeFormattedTime === formattedTime;
  }

  const openStationACFromEachTrainInfo = async (stationName) => {
    await SheetManager.hide("EachTrainInfo");
    const findStationEachLine = (selectLine) => {
      let NearStation = selectLine.filter((d) => d.Station_JP == stationName);
      return NearStation;
    };
    let returnDataBase = lineList
      .map((d) => findStationEachLine(originalStationList[d]))
      .filter((d) => d.length > 0)
      .reduce((pre, current) => {
        pre.push(...current);
        return pre;
      }, []);
    if (returnDataBase.length) {
      const payload = {
        currentStation: returnDataBase,
        navigate,
        //@ts-ignore
        useShow: () => SheetManager.show("StationDetailView", { payload }),
        onExit: () => SheetManager.hide("StationDetailView"),
      }; //@ts-ignore
      setTimeout(() => SheetManager.show("StationDetailView", { payload }), 50);
    } else {
      SheetManager.hide("StationDetailView");
    }
  };
  const openTrainInfo = () => {
    let TrainNumber = "";
    if (trainData.trainNumDistance != undefined) {
      const timeInfo =
        parseInt(trainData.TrainNumber.replace("M", "").replace("D", "")) -
        trainData.trainNumDistance;
      TrainNumber = timeInfo + "号";
    }
    const payload = {
      data: {
        trainNum: trainData.TrainNumber,
        limited: `${data}:${trainData.trainName}${TrainNumber}`,
      },
      navigate,
      openStationACFromEachTrainInfo,
      from: d.isOperating ? null :"AllTrainIDList",
    };
    SheetManager.show("EachTrainInfo", {
      //@ts-ignore
      payload,
      onClose: (data) => {
        //alert(data);
      },
    });
  };
  const [stationColor, setStationColor] = useState(["gray"]);
  useEffect(() => {
    const Stations = stationList
      .map((a) => a.filter((d) => d.StationName == trainName))
      .reduce((newArray, e) => newArray.concat(e), []);
    const StationNumbers =
      Stations &&
      Stations.filter((d) => d.StationNumber).map((d) => d.StationNumber);

    if (StationNumbers) {
      const stationLineColor = StationNumbers.map(
        (d) => lineColorList[d.charAt(0)]
      );
      setStationColor(stationLineColor || ["gray"]);
    }
  }, [stationList]);
  // if(typeString == "回送"){
  //   return<></>;
  // }
  const animatedStyle = useAnimatedStyle(() => {
    const leftPosition =
      ((((width.value - 50) / 100) * parseInt(formattedTime)) / 60) * 100;
    return {
      left: leftPosition,
    };
  }, [formattedTime]);
  return (
    <View style={{ left: 0, height: 50 }}>
      <Animated.View
        style={[
          {
            flexDirection: "column",
            //borderTopWidth: 1,
            //borderBottomWidth: 0.5,
            borderStyle: "solid",
            borderColor: "darkgray",
            opacity: d.type.includes("通") ? 0.5 : 1,
            position: "absolute",
            height: "100%",
            width: 28,
            top: isSameTimeBefore ? 10 : 0,
          },
          animatedStyle,
        ]}
      >
        <TouchableOpacity style={{ flex: 1 }} onPress={() => openTrainInfo()}>
          <View style={{ position: "relative" }}>
            <Text style={{ fontSize: 20, color: color, opacity: isSameTimeBefore ? 0 : 1, fontWeight:d.isOperating ? "bold" : "thin", fontStyle:d.isOperating? "italic" :"normal" }}>{formattedTime}</Text>
            <Text
              style={{
                fontSize: 10,
                position: "absolute",
                bottom: 0,
                right: 0,
                fontWeight: "bold",
              }}
            >
              {d.type}
            </Text>
          </View>
          <View style={{ flex: 1, flexDirection: "column" }}>
            <Text
              style={{
                fontSize: 8,
                flex: 1,
                fontWeight: "bold",
                color: stationColor[0],
              }}
            >
              {trainName}
            </Text>
          </View>
        </TouchableOpacity>
      </Animated.View>
    </View>
  );
};
