import React, { FC, useEffect, useState } from "react";
import { TouchableOpacity } from "react-native";
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 "@/components/発車時刻表/LED_inside_Component/Description";
import { DependTime } from "@/components/発車時刻表/LED_inside_Component/DependTime";
import { LastStation } from "@/components/発車時刻表/LED_inside_Component/LastStation";
import { StatusAndDelay } from "@/components/発車時刻表/LED_inside_Component/StatusAndDelay";
import { TrainName } from "@/components/発車時刻表/LED_inside_Component/TrainName";
import { TrainPosition } from "@/components/発車時刻表/LED_inside_Component/TrainPosition";
import { StationPosPushDialog } from "@/components/発車時刻表/LED_inside_Component/TrainPositionDataPush";
import { StationPosDeleteDialog } from "@/components/発車時刻表/LED_inside_Component/TrainPositionDataDelete";
import { useStationList } from "@/stateBox/useStationList";
import useInterval from "@/lib/useInterval";
import dayjs from "dayjs";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { CustomTrainData, StationProps, trainTypeID } from "@/lib/CommonTypes";
import { getCurrentTrainData } from "@/lib/getCurrentTrainData";

type Props = {
  d: {
    train: string;
    lastStation: string;
    time: string;
    isThrough?: boolean;
  };
  trainIDSwitch: boolean;
  trainDescriptionSwitch: boolean;
  station: StationProps;
  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({type:train.type}).data}:${
          train.trainName
        }${TrainNumber}`,
      },
      navigate,
      openStationACFromEachTrainInfo,
      from: "LED",
    };
    SheetManager.show("EachTrainInfo", {
      payload,
    });
  };

  const [train, setTrain] = useState<CustomTrainData>(getCurrentTrainData(d.train,currentTrain,allCustomTrainData));
  useEffect(() => {
    setTrain(getCurrentTrainData(d.train,currentTrain,allCustomTrainData));
  }, [currentTrain, d.train, trainDescriptionSwitch]);
  // 土讃線複数存在対策
  const currentTrainData = checkDuplicateTrainData(
    currentTrain.filter((a) => a.num == d.train),
    stationList
  );
  const trainDelayStatus = `${getTrainDelayStatus(
    currentTrainData,
    station.Station_JP
  )}`;

  // 投稿システム関係
  // Dialog表示関係
  const [dialog, setDialog] = useState(false);
  const [deleteDialog, setDeleteDialog] = useState(false);
  //固定値
  const [PosNum, setPosNum] = useState<number | undefined>();
  const [Pos, setPos] = useState<string>("");
  const [Line, setLine] = useState<string>("");
  const [StationNum, setStationNum] = useState<string>("");

  //編集情報
  const [lineInput, setLineInput] = useState<string>("");
  const [posInput, setPosInput] = useState<string>("");
  const [descInput, setDescInput] = useState<string>("");

  const [isShow, setIsShow] = useState(true);
  const [isDepartureNow, setIsDepartureNow] = useState(false);
  useEffect(() => {
    const [h, m] = d.time.split(":");
    const IntH = parseInt(h);
    const IntM = parseInt(m);
    const currentTime = dayjs();
    const trainTime = currentTime
      .set("hour", IntH < 4 ? IntH + 24 : IntH)
      .set("minute", IntM);
    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 (
    <>
      <StationPosDeleteDialog
        dialog={deleteDialog}
        setDialog={setDeleteDialog}
        Pos={Pos}
        PosNum={PosNum}
        Line={Line}
        StationNum={StationNum}
      />
      <StationPosPushDialog
        // Dialog表示関係
        dialog={dialog}
        setDialog={setDialog}
        // 固定情報
        PosNum={PosNum}
        Pos={Pos}
        Line={Line}
        StationNum={StationNum}
        // 入力欄
        lineInput={lineInput}
        setLineInput={setLineInput}
        posInput={posInput}
        setPosInput={setPosInput}
        descInput={descInput}
        setDescInput={setDescInput}
      />
      <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}
          isThrew={d.isThrough}
        />
        <LastStation lastStation={d.lastStation} ToData={train.ToData} Station_JP={station.Station_JP} />
        <DependTime time={d.time} />
        <StatusAndDelay trainDelayStatus={trainDelayStatus} />
      </TouchableOpacity>
      {!!isDepartureNow && (
        <Description
          info={
            d.isThrough
              ? "通過列車にご注意ください"
              : d.lastStation == station.Station_JP
              ? "この列車は当駅止です。間もなく到着します。"
              : "列車の出発時刻です。"
          }
          key={d.train + "-isDepartureNow"}
        />
      )}
      {trainDescriptionSwitch && (
        <TrainPosition
          // LED表示関係
          trainIDSwitch={trainIDSwitch}
          currentTrainData={currentTrainData}
          // ポップアップ表示関係
          setDialog={setDialog}
          setDeleteDialog={setDeleteDialog}
          // 固定情報
          setPos={setPos}
          setPosNum={setPosNum}
          setLine={setLine}
          setStationNum={setStationNum}
          //編集機能関係
          setLineInput={setLineInput}
          setPosInput={setPosInput}
          setDescInput={setDescInput}
          key={d.train + "-trainPosition"}
        />
      )}
      {trainDescriptionSwitch && !!train.info && (
        <Description info={train.info} key={d.train + "-description"} />
      )}
      {trainDescriptionSwitch && !!train.uwasa && (
        <Description info={train.uwasa} key={d.train + "-uwasa"} />
      )}
    </>
  );
};
