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 = {
  numberOfLines?: number;
  trainIDSwitch: boolean;
  currentTrainData: trainDataType;
  setStationInput: (station: string) => void;
  setStationNumberInput: (station: string) => void;
  setDescInput: (desc: string) => void;
  setPosInput: (pos: string) => void;
  setDialog: (dialog: boolean) => void;
  setDeleteDialog: (dialog: boolean) => void;
  platformDescription: string;
  platformNumber: string;
  setPlatformDescription: (desc: string) => void;
  setPlatformNumber: (num: string) => void;
  lineInput: string;
  setLineInput: (line: string) => void;
};

export const TrainPosition: FC<Props> = ({
  numberOfLines = 0,
  trainIDSwitch,
  currentTrainData,
  setStationInput,
  setStationNumberInput,
  setDescInput,
  setPosInput,
  setDialog,
  setDeleteDialog,
  setPlatformDescription,
  setPlatformNumber,
  platformDescription,
  platformNumber,
  setLineInput,
}) => {
  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]);

  return (
    <TouchableOpacity
      style={{
        alignContent: "center",
        alignItems: "center",
        width: "94%",
        marginVertical: 5,
        marginHorizontal: "3%",
        backgroundColor: "#000",
        flexDirection: "row",
        overflow: "hidden",
      }}
      onLongPress={() => {
        const { isBetween, Pos } = trainPosition(currentTrainData);
        setStationNumberInput(getStationID(currentTrainData?.Pos, stationList));
        setPosInput(database?.platformNumber?.toString() || "");
        if (isBetween === true) {
          if (database?.platformNumber == undefined && database?.description == undefined)
            return;
          setStationInput(`${Pos.from}→${Pos.to}間`);
          setDeleteDialog(true);
        } else {
          setStationInput(currentTrainData?.Pos);
          setDescInput(database?.description || "");
          setLineInput(database?.lineNumber?.toString() || "");
          setPlatformNumber(database?.platformNumber?.toString() || "");
          setDialog(true);
        }
      }}
    >
      <View style={{ flex: 4, flexDirection: "row" }}>
        <Text
          style={{ ...descriptionStyle, color: "green" }}
          numberOfLines={numberOfLines}
        >
          {text}
        </Text>
      </View>
    </TouchableOpacity>
  );
};
