import React, { useState, useEffect } from "react";
import { View, TouchableOpacity, useWindowDimensions } from "react-native";
import { StateBox } from "./StateBox";
import { useDeviceOrientationChange } from "../../../stateBox/useDeviceOrientationChange";
import { getStationList2 } from "../../../lib/getStationList2";
import { useCurrentTrain } from "../../../stateBox/useCurrentTrain";
import { SheetManager } from "react-native-actions-sheet";
import { trainPosition } from "../../../lib/trainPositionTextArray";
import { TrainPositionDataPush } from "../../発車時刻表/LED_inside_Component/TrainPositionDataPush";
import { getStationID } from "../../../lib/eachTrainInfoCoreLib/getStationData";
import { useStationList } from "../../../stateBox/useStationList";

export const TrainDataView = ({
  currentTrainData,
  currentPosition,
  nearTrainIDList,
  openTrainInfo,
  mode = 0,
  navigate,
}) => {
  const { stationList } = useStationList();

  const { width, height } = useWindowDimensions();
  const { isLandscape } = useDeviceOrientationChange();
  const { inject } = useCurrentTrain();
  const [mapsStationData, setMapsStationData] = useState(undefined);

  const [platformNumber, setPlatformNumber] = useState();
  const [platformDescription, setPlatformDescription] = useState();
  useEffect(() => {
    //currentTrainData.Pos = "鴨川～端岡"; //test
    if (!currentTrainData) return;
    fetch(
      `https://n8n.haruk.in/webhook/JR-shikoku-PosID?PosNum=${currentTrainData?.PosNum}&Line=${currentTrainData?.Line}`
    )
      .then((res) => res.json())
      .then((data) => {
        setPlatformNumber(data?.type == "Station" ? data?.platform : undefined);
        setPlatformDescription(
          data?.type == "Station" ? data?.description : undefined
        );
      });
  }, [currentTrainData]);
  useEffect(() => {
    getStationList2().then(setMapsStationData);
  }, []);
  const onLine = !!currentPosition?.toString().length;
  const trainPositionText = (trainData) => {
    const { isBetween, Pos: PosData } = trainPosition(trainData);
    const { from, to, Pos } = PosData;
    if (isBetween === true) return `${from}～${to}`;
    if (Pos == "") return "";
    return `${Pos}${platformNumber ? ` ${platformNumber}番線` : ""}`;
  };
  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("");
  return (
    <>
      <TrainPositionDataPush
        dialog={dialog}
        setDialog={setDialog}
        currentTrainData={currentTrainData}
        stationInput={stationInput}
        stationNumberInput={stationNumberInput}
        posInput={posInput}
        descInput={descInput}
        setPosInput={setPosInput}
        setDescInput={setDescInput}
        station={{
          Station_JP: trainPositionText(currentTrainData),
          StationNumber: currentPosition[0],
        }}
      />
      <View
        style={{
          flexDirection: "row",
          //minHeight: 200,
          //height: heightPercentageToDP("20%"),
          width: isLandscape ? (width / 100) * 40 : width,
          flex: 1,
        }}
      >
        <TouchableOpacity
          style={{ flex: 1, flexDirection: "row" }}
          //disabled={!onLine}
          onLongPress={() => {
            const { isBetween, Pos } = trainPosition(currentTrainData);
            if (isBetween === true) {
              if (
                platformNumber == undefined &&
                platformDescription == undefined
              )
                return;
              setStationInput(`${Pos.from}→${Pos.to}間`);
              setStationNumberInput(
                getStationID(currentTrainData?.Pos, stationList)
              );
              setPosInput(platformNumber?.toString() || "");
              setDeleteDialog(true);
            } else {
              setStationInput(Pos.Pos);
              setStationNumberInput(
                getStationID(currentTrainData?.Pos, stationList)
              );
              setDescInput(platformDescription || "");
              setPosInput(platformNumber?.toString() || "");
              setDialog(true);
            }
          }}
          onPress={() => {
            if (!onLine) return;
            const test = [];
            Object.keys(mapsStationData).forEach((d) => {
              mapsStationData[d].forEach((x) => {
                if (x.StationNumber == currentPosition[0])
                  test.push({ line: d, station: x });
              });
              if (currentPosition[0] == "M12") {
                test.push({
                  line: "seto",
                  station: { Station_JP: "児島", MyStation: "0" },
                });
              }
            });
            if (!test.length) return;
            navigate("positions", { screen: "Apps" });
            inject(
              `MoveDisplayStation('${test[0].line}_${test[0].station.MyStation}_${test[0].station.Station_JP}');document.getElementById("disp").insertAdjacentHTML("afterbegin", "<div />");`
            );
            SheetManager.hide("EachTrainInfo");
          }}
        >
          <StateBox
            mode={mode}
            title={`現在地 ${currentPosition?.toString()}${onLine ? "▶️" : ""}`}
            text={trainPositionText(currentTrainData)}
            endText={platformDescription ? `${platformDescription}` : ""}
            style={
              onLine
                ? { borderWidth: 1, borderColor: "red", borderStyle: "solid" }
                : {}
            }
          />
        </TouchableOpacity>

        <View style={{ flex: 1, flexDirection: mode == 2 ? "row" : "column" }}>
          <View style={{ flex: 1, flexDirection: "row" }}>
            <StateBox
              mode={mode}
              title={isNaN(currentTrainData?.delay) ? "状態" : "遅延時分"}
              text={`${currentTrainData?.delay}${
                isNaN(currentTrainData?.delay) ? "" : "分"
              }`}
            />
          </View>
          <TouchableOpacity
            style={{ flex: 1, flexDirection: "row" }}
            disabled={nearTrainIDList.length == 0}
            onPress={() => {
              if (nearTrainIDList.length == 0) return;
              openTrainInfo(nearTrainIDList[0]);
            }}
          >
            {nearTrainIDList.length == 0 ? (
              <StateBox mode={mode} title="列番" text={currentTrainData?.num} />
            ) : (
              <StateBox
                mode={mode}
                title="増解結相手を表示▶️"
                text={`${nearTrainIDList}`}
                style={{
                  borderWidth: 1,
                  borderColor: "red",
                  borderStyle: "solid",
                }}
              />
            )}
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
};
