import { migrateTrainName } from "@/lib/eachTrainInfoCoreLib/migrateTrainName";
import { getStringConfig } from "@/lib/getStringConfig";
import { getTrainType } from "@/lib/getTrainType";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { FC, useEffect, useMemo, useState } from "react";
import { View, Text, TouchableOpacity } 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 { CustomTrainData, trainTypeID } from "@/lib/CommonTypes";
import { StationNumberMaker } from "../駅名表/StationNumberMaker";
import { getStationID } from "@/lib/eachTrainInfoCoreLib/getStationData";
import lineColorList from "@/assets/originData/lineColorList";

export const ListViewItem: FC<{
  d: {
    trainNumber: string;
    array: string;
    name: string;
    timeType: string;
    time: string;
  };
}> = ({ d }) => {
  const { allCustomTrainData } = useAllTrainDiagram();
  const { navigate, goBack } = useNavigation();
  const [trainData, setTrainData] = useState<CustomTrainData>();
  useEffect(() => {
    if (allCustomTrainData) {
      allCustomTrainData.forEach((x) => {
        if (x.TrainNumber === d.trainNumber) {
          setTrainData(x);
        }
      });
    }
  }, []);
  const { color, name, data } = getTrainType({
    type: trainData?.type,
    whiteMode: true,
  });
  // 列車名、種別、フォントの取得
    const { getStationDataFromName, stationList, originalStationList } =
    useStationList();
  const [
    typeString,
    trainName,
    fontAvailable,
    isOneMan,
    infogram,
    isEdit,
    uwasa,
    vehicleFormation,
    trainInfoUrl,lineColor
  ] = 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 !== "");
    const station = getStationDataFromName(trainData[trainData.length - 1].split(",")[0]);
    const lineColor =
        station.length > 0
          ? lineColorList[station[0]?.StationNumber.slice(0, 1)]
          : "black";
    switch (true) {
      case trainData[trainData.length - 1] === undefined:
        return [
          typeString,
          "",
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,lineColor
        ];
      default:
        // 行先がある場合は、行先を取得
        return [
          typeString,
          migrateTrainName(
            trainData[trainData.length - 1].split(",")[0] + "行き"
          ),
          fontAvailable,
          isOneMan,
          infogram,
          isEdit,
          uwasa,
          vehicleFormation,
          trainInfoUrl,lineColor
        ];
    }
  }, [d.array]);
  const timeArray = d.time.split(":").map((s) => parseInt(s));
  const formattedTime = dayjs()
    .set("hour", timeArray[0])
    .set("minute", timeArray[1])
    .format("HH:mm");

  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: "AllTrainIDList",
    };
    SheetManager.show("EachTrainInfo", {
      //@ts-ignore
      payload,
      onClose: (data) => {
        //alert(data);
      },
    });
  };
  return (
    <TouchableOpacity
      style={{
        flexDirection: "row",
        marginHorizontal: 10,
        borderTopWidth: 1,
        borderBottomWidth: 0.5,
        borderStyle: "solid",
        borderColor: "darkgray",
        padding: 10,
        opacity: d.timeType?.includes("通") ? 0.5 : 1,
      }}
      onPress={() => openTrainInfo()}
    >
      <View style={{ position: "relative", flex: 3 }}>
        <Text style={{ fontSize: 30, fontFamily: "DiaPro" }}>
          {formattedTime}
        </Text>
        <Text
          style={{
            fontSize: 10,
            position: "absolute",
            bottom: -3,
            right: 0,
            fontWeight: "bold",
          }}
        >
          {d.timeType}
        </Text>
      </View>
      <View style={{ flex: 10, flexDirection: "column" }}>
        <View style={{ flexDirection: "row" }}>
          <Text
            style={{
              fontSize: 15,
              fontFamily: fontAvailable ? "JR-Nishi" : undefined,
              fontWeight: !fontAvailable ? "bold" : undefined,
              paddingTop: fontAvailable ? 2 : 0,
              paddingLeft: 10,
              color: color,
            }}
          >
            {typeString}
          </Text>
          <Text
            style={{
              fontSize: 15,
              fontWeight: "bold",
              flex: 1,
              paddingLeft: 2,
              color: color,
            }}
          >
            {trainData?.trainName +
              (trainData?.trainNumDistance !== null
                ? ` ${parseInt(d.trainNumber) - trainData?.trainNumDistance}号`
                : "")}
          </Text>
          <Text
            style={{
              fontSize: 15,
              fontWeight: "bold",
            }}
          >
            {trainData?.TrainNumber}
          </Text>
        </View>
        <View style={{ flexDirection: "row", alignItems: "center", flex: 1 }}>
          <Text
            style={{
              fontSize: 15,
              flex: 1,
              paddingHorizontal: 10,
              fontWeight: "bold",
              color: lineColor
            }}
          >
            {trainName}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};
