import React, { FC, useEffect, useState } from "react";
import { Linking, TouchableOpacity, Text } from "react-native";
import { Dialog, Button, Input } from "react-native-elements";
import { checkDuplicateTrainData } from "../../lib/checkDuplicateTrainData";
import { getTrainDelayStatus } from "../../lib/getTrainDelayStatus";
import { getTrainType } from "../../lib/getTrainType";
import { useCurrentTrain } from "../../stateBox/useCurrentTrain";
import { SheetManager } from "react-native-actions-sheet";
import { Description } from "./LED_inside_Component/Description";
import { DependTime } from "./LED_inside_Component/DependTime";
import { LastStation } from "./LED_inside_Component/LastStation";
import { StatusAndDelay } from "./LED_inside_Component/StatusAndDelay";
import { TrainName } from "./LED_inside_Component/TrainName";
import { customTrainDataDetector } from "../custom-train-data";
import { TrainPosition } from "./LED_inside_Component/TrainPosition";
import { TrainPositionDataPush } from "./LED_inside_Component/TrainPositionDataPush";
import { TrainPositionDataDelete } from "./LED_inside_Component/TrainPositionDataDelete";
import { useStationList } from "../../stateBox/useStationList";
import useInterval from "@/lib/useInterval";
import dayjs from "dayjs";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";

type Props = {
  d: {
    train: string;
    lastStation: string;
    time: string;
  };
  trainIDSwitch: boolean;
  trainDescriptionSwitch: boolean;
  station: {
    Station_JP: string;
    StationNumber: string;
  };
  navigate: (screen: string, data?: any) => void;
  openStationACFromEachTrainInfo: (station: string) => void;
};
export const EachData: FC<Props> = (props) => {
  const {
    d,
    trainIDSwitch,
    trainDescriptionSwitch,
    station,
    navigate,
    openStationACFromEachTrainInfo,
  } = props;
  const { currentTrain } = useCurrentTrain();
  const { stationList } = useStationList();
  const { allCustomTrainData } = useAllTrainDiagram();
  const openTrainInfo = (d: {
    train: string;
    lastStation: string;
    time: string;
  }) => {
    let TrainNumber = "";
    if (train.trainNumDistance != undefined) {
      const timeInfo =
        parseInt(d.train.replace("M", "").replace("D", "")) -
        train.trainNumDistance;
      TrainNumber = timeInfo + "号";
    }
    const payload = {
      data: {
        trainNum: d.train,
        limited: `${getTrainType(train.type).data}:${
          train.trainName
        }${TrainNumber}`,
      },
      navigate,
      openStationACFromEachTrainInfo,
      from: "LED",
    };
    SheetManager.show("EachTrainInfo", {
      payload,
    });
  };

  const getTrainDataFromCurrentTrain = (trainNum: string) => {
    const customTrainData = customTrainDataDetector(
      d.train,
      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(getTrainDataFromCurrentTrain(d.train));
  useEffect(() => {
    setTrain(getTrainDataFromCurrentTrain(d.train));
  }, [currentTrain, d.train, trainDescriptionSwitch]);
  // 土讃線複数存在対策
  const currentTrainData = checkDuplicateTrainData(
    currentTrain.filter((a) => a.num == d.train),
    stationList
  );
  const trainDelayStatus = `${getTrainDelayStatus(
    currentTrainData,
    station.Station_JP
  )}`;

  const [platformNumber, setPlatformNumber] = useState<number>();
  const [platformDescription, setPlatformDescription] = useState<string>();

  const [dialog, setDialog] = useState(false);
  const [deleteDialog, setDeleteDialog] = useState(false);
  const [posInput, setPosInput] = useState("");
  const [descInput, setDescInput] = useState("");
  const [stationInput, setStationInput] = useState("");
  const [stationNumberInput, setStationNumberInput] = useState("");

  const [isShow, setIsShow] = useState(true);
  const [isDepartureNow, setIsDepartureNow] = useState(false);
  useEffect(() => {
    const currentTime = dayjs();
    const trainTime = currentTime
      .set("hour", parseInt(d.time.split(":")[0]))
      .set("minute", parseInt(d.time.split(":")[1]));
    const diff = trainTime.diff(currentTime, "minute");
    if (diff < 2) setIsDepartureNow(true);
    else setIsDepartureNow(false);
    return () => {
      setIsDepartureNow(false);
      setIsShow(true);
    };
  }, [d.time, currentTrainData]);
  useInterval(() => {
    if (isDepartureNow) {
      setIsShow(!isShow);
    }
  }, 800);
  return (
    <>
      <TrainPositionDataDelete
        dialog={deleteDialog}
        setDialog={setDeleteDialog}
        {...{ currentTrainData, stationInput, stationNumberInput }}
      />
      <TrainPositionDataPush
        dialog={dialog}
        setDialog={setDialog}
        {...{
          currentTrainData,
          stationInput,
          stationNumberInput,
          posInput,
          descInput,
          setPosInput,
          setDescInput,
          station,
        }}
      />
      <TouchableOpacity
        style={{
          alignContent: "center",
          alignItems: "center",
          width: "94%",
          marginVertical: 5,
          marginHorizontal: "3%",
          backgroundColor: "#000",
          flexDirection: "row",
          opacity: isShow ? 1 : 0.5,
        }}
        onPress={() => openTrainInfo(d)}
        key={d.train + "-eachData"}
      >
        <TrainName
          trainName={train.trainName}
          trainNumDistance={train.trainNumDistance}
          trainIDSwitch={trainIDSwitch}
          trainID={d.train}
          type={train.type}
        />
        <LastStation lastStation={d.lastStation} />
        <DependTime time={d.time} />
        <StatusAndDelay trainDelayStatus={trainDelayStatus} />
      </TouchableOpacity>
      {!!isDepartureNow && (
        <Description
          info={
            d.lastStation == "当駅止"
              ? "この列車は当駅止です。間もなく到着します。"
              : "列車の出発時刻です。"
          }
          key={d.train + "-description"}
        />
      )}
      {trainDescriptionSwitch && (
        <TrainPosition
          trainIDSwitch={trainIDSwitch}
          currentTrainData={currentTrainData}
          setStationInput={setStationInput}
          setStationNumberInput={setStationNumberInput}
          setDescInput={setDescInput}
          setPosInput={setPosInput}
          setDialog={setDialog}
          setDeleteDialog={setDeleteDialog}
          setPlatformDescription={setPlatformDescription}
          setPlatformNumber={setPlatformNumber}
          platformDescription={platformDescription}
          platformNumber={platformNumber}
          key={d.train + "-trainPosition"}
        />
      )}
      {trainDescriptionSwitch && !!train.info && (
        <Description info={train.info} key={d.train + "-description"} />
      )}
    </>
  );
};
