import React, { useState, useEffect, FC } from "react";
import { View, TouchableOpacity, useWindowDimensions } from "react-native";
import { StateBox } from "./StateBox";
import { PositionBox } from "./PositionBox";
import { useDeviceOrientationChange } from "../../../stateBox/useDeviceOrientationChange";
import { getStationList2 } from "../../../lib/getStationList";
import { useCurrentTrain } from "../../../stateBox/useCurrentTrain";
import { SheetManager } from "react-native-actions-sheet";
import { trainDataType, trainPosition } from "@/lib/trainPositionTextArray";
import { StationPosPushDialog } from "../../発車時刻表/LED_inside_Component/TrainPositionDataPush";
import { getStationID } from "../../../lib/eachTrainInfoCoreLib/getStationData";
import { useStationList } from "../../../stateBox/useStationList";
import { useAllTrainDiagram } from "@/stateBox/useAllTrainDiagram";
import { customTrainDataDetector } from "@/components/custom-train-data";


type props = {
  currentTrainData: trainDataType;
  currentPosition: string[] | undefined;
  nearTrainIDList: string[];
  openTrainInfo: (f: string) => void;
  mode?: 0 | 1 | 2; //0:通常,1:コンパクト,2:横並び
  navigate: (screen: string, data?: any) => void;
}
export const TrainDataView:FC<props> = ({
  currentTrainData,
  currentPosition,
  nearTrainIDList,
  openTrainInfo,
  mode = 0,
  navigate,
}) => {
  const { stationList } = useStationList();

  const { width, height } = useWindowDimensions();
  const { isLandscape } = useDeviceOrientationChange();
  const { setInjectData } = useCurrentTrain();

  const { allCustomTrainData } = useAllTrainDiagram();
  const [mapsStationData, setMapsStationData] = useState(undefined);

  const [platformNumber, setPlatformNumber] = useState();
  const [lineNumber, setLineNumber] = useState();
  const [platformDescription, setPlatformDescription] = useState();
  type data = {
    type: string;
    lineNumber: string;
    platformNumber: string;
    position: string;
    stationName: string;
    description: string;
  };
  const [database, setDatabase] = useState<data>(null);
  useEffect(() => {
    //currentTrainData.Pos = "鴨川～端岡"; //test
    if (!currentTrainData) return;
    fetch(
      `https://n8n.haruk.in/webhook/JR-shikoku-PosID-v3?PosId=${currentTrainData?.PosNum}&lineName=${currentTrainData?.Line}&StationName=${currentTrainData?.Pos}`
    )
      .then((res) => res.json())
      .then((data) => {
        if (!data) return;
        const {
          type,
          stationName,
          lineNumber,
          platformNumber,
          position,
          description,
        } = data;
        setDatabase(data);
        if (type == "Station") {
          setLineNumber(lineNumber);
          setPlatformNumber(platformNumber);
          setPlatformDescription(description);
        } else {
          setLineNumber(undefined);
          setPlatformNumber(undefined);
          setPlatformDescription(undefined);
        }
      });
  }, [currentTrainData]);
  useEffect(() => {
    getStationList2().then(setMapsStationData);
  }, []);
  const onLine = !!currentPosition?.toString().length;

  const [trainNumber, setTrainNumber] = useState(currentTrainData?.num);
  useEffect(() => {
    const { TrainNumberOverride } = customTrainDataDetector(
      currentTrainData?.num,
      allCustomTrainData
    );
    if (TrainNumberOverride) {
      setTrainNumber(TrainNumberOverride);
    }else{
      setTrainNumber(currentTrainData?.num);
    }
  }, [currentTrainData?.num, allCustomTrainData]);
  // 投稿システム関係
  // 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 openEditWindow = () => {
    const { isBetween, Pos } = trainPosition(currentTrainData);
    if (isBetween === true) return;
    //固定値
    setPosNum(currentTrainData?.PosNum);
    setPos(currentTrainData?.Pos);
    setLine(currentTrainData?.Line);
    setStationNum(getStationID(currentTrainData?.Pos, stationList));

    //入力欄
    setPosInput(database?.platformNumber?.toString() || "");
    setDescInput(database?.description || "");
    setLineInput(database?.lineNumber?.toString() || "");
    setDialog(true);
  };

  return (
    <>
      <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}
      />
      <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={openEditWindow}
          onLongPress={()=>{
            if (!onLine) return;
            setInjectData({ type:"train", value:currentTrainData?.num, fixed:true});
            navigate("positions", { screen: "Apps" });
            SheetManager.hide("EachTrainInfo");
          }}
          onPress={() => {
            if (!onLine) return;
            setInjectData({ type: "station", value: currentPosition[0], fixed: false });
            
            navigate("positions", { screen: "Apps" });
            SheetManager.hide("EachTrainInfo");
          }}
        >
          <PositionBox
            mode={mode}
            title={`現在地 ${currentPosition?.toString()}${onLine ? "▶️" : ""}`}
            currentTrainData={currentTrainData}
            platformNumber={platformNumber}
            lineNumber={lineNumber}
            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={trainNumber} />
            ) : (
              <StateBox
                mode={mode}
                title="増解結相手を表示▶️"
                text={`${nearTrainIDList}`}
                style={{
                  borderWidth: 1,
                  borderColor: "red",
                  borderStyle: "solid",
                }}
              />
            )}
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
};
