import React, { FC, useEffect, useState } from "react";
import { Text, TextStyle, View, TouchableOpacity } from "react-native";
import { useStationList } from "../../../stateBox/useStationList";
import {
  trainDataType,
  trainPosition,
} from "../../../lib/trainPositionTextArray";
import { getStationID } from "../../../lib/eachTrainInfoCoreLib/getStationData";
import { useCurrentTrain } from "../../../stateBox/useCurrentTrain";

const descriptionStyle: TextStyle = {
  fontSize: parseInt("16%"),
  fontWeight: "bold",
};

type Props = {
  // LED表示関係
  numberOfLines?: number;
  trainIDSwitch: boolean;
  currentTrainData: trainDataType;
  //ポップアップ表示関係
  setDialog: (dialog: boolean) => void;
  setDeleteDialog: (dialog: boolean) => void;

  //固定値設定
  setPos: React.Dispatch<React.SetStateAction<string>>
  setPosNum: React.Dispatch<React.SetStateAction<number>>;
  setLine: React.Dispatch<React.SetStateAction<string>>;
  setStationNum: React.Dispatch<React.SetStateAction<string>>;

  //編集機能関係
  setLineInput: (line: string) => void;
  setPosInput: (pos: string) => void;
  setDescInput: (desc: string) => void;
};

export const TrainPosition: FC<Props> = ({
  // LED表示関係
  numberOfLines = 0,
  trainIDSwitch,
  currentTrainData,
  //ポップアップ表示関係
  setDialog,
  setDeleteDialog,

  //固定値設定
  setPos,
  setPosNum,
  setLine,
  setStationNum,

  //編集機能関係
  setLineInput,
  setPosInput,
  setDescInput,

}) => {
  const { stationList } = useStationList();
  type data = {
    type: string;
    lineNumber: string;
    platformNumber: string;
    position: string;
    stationName: string;
    description: string;
  };
  const [database, setDatabase] = useState<data>(null);
  const [text, setText] = useState("");
  const [masterText, setMasterText] = useState("");
  useEffect(() => {
    const text = `${currentTrainData?.PosNum} ${currentTrainData?.Line} ${currentTrainData?.Pos}`;
    setText(trainIDSwitch ? text : masterText);
    return () => {
      setText("");
    };
  }, [masterText, trainIDSwitch]);
  useEffect(() => {
    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: data) => {
        const { type, platformNumber, description, lineNumber } = data;
        setDatabase(data);
        const { isBetween, Pos } = trainPosition(currentTrainData);
        if (isBetween === true) {
          // 移動中
          setMasterText(`現在地：${Pos.from}→${Pos.to}間を走行中`);
        } else {
          if (Pos.Pos) {
            let platform = platformNumber ? `${platformNumber}番乗り場` : "";
            let line = lineNumber ? `${lineNumber}番線` : "";
            setMasterText(
              `現在地：${Pos.Pos}  ${platform || line} ${description || ""}`
            );
          } else {
            setMasterText("");
          }
        }
      });
    return () => {
      setMasterText("");
    };
  }, [currentTrainData?.PosNum, currentTrainData?.Line, currentTrainData?.Pos]);
  //editWindow向けにfixした情報を送信
  const openEditWindow = () => {
    const { isBetween, Pos } = trainPosition(currentTrainData);

    //固定値
    setPosNum(currentTrainData?.PosNum);
    setPos(currentTrainData?.Pos);
    setLine(currentTrainData?.Line);
    setStationNum(getStationID(currentTrainData?.Pos, stationList));

    //入力欄
    if (isBetween === true) {
      if (
        database?.platformNumber == undefined &&
        database?.description == undefined
      )
        return;
      setDeleteDialog(true);
    } else {
      setPosInput(database?.platformNumber?.toString() || "");
      setDescInput(database?.description || "");
      setLineInput(database?.lineNumber?.toString() || "");
      setDialog(true);
    }
  };

  return (
    <TouchableOpacity
      style={{
        alignContent: "center",
        alignItems: "center",
        width: "94%",
        marginVertical: 5,
        marginHorizontal: "3%",
        backgroundColor: "#000",
        flexDirection: "row",
        overflow: "hidden",
      }}
      onLongPress={openEditWindow}
    >
      <View style={{ flex: 4, flexDirection: "row" }}>
        <Text
          style={{ ...descriptionStyle, color: "green" }}
          numberOfLines={numberOfLines}
        >
          {text}
        </Text>
      </View>
    </TouchableOpacity>
  );
};
