import React, { useRef, useState, useEffect, useLayoutEffect } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  useWindowDimensions,
} from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import LottieView from "lottie-react-native";
import { useInterval } from "../../lib/useInterval";
import { AS } from "../../storageControl";
import { useFavoriteStation } from "../../stateBox/useFavoriteStation";

import { StationNameArea } from "./StationNameArea";
import { StationNumberMaker } from "./StationNumberMaker";
import { NextPreStationLine } from "./NextPreStationLine";
import { LottieDelayView } from "./LottieDelayView";
import { AddressText } from "./AddressText";
import { useStationList } from "../../stateBox/useStationList";

export default function Sign(props) {
  const { oP, oLP, isCurrentStation = false, stationID } = props;

  const { width, height } = useWindowDimensions();
  const { getStationDataFromId } = useStationList();
  if (!stationID) {
    return <></>;
  }
  const [currentStationData] = useState(getStationDataFromId(stationID));
  const { favoriteStation, setFavoriteStation } = useFavoriteStation();
  const [nexPrePosition, setNexPrePosition] = useState(0);
  const { originalStationList } = useStationList();

  const [preStation, setPreStation] = useState();
  const [nexStation, setNexStation] = useState();
  const [testButtonStatus, setTestButtonStatus] = useState(false);
  useLayoutEffect(() => {
    const isFavorite = favoriteStation.filter((d) => {
      const compare = JSON.stringify(d);
      const current = JSON.stringify(currentStationData);
      return compare === current;
    });
    setTestButtonStatus(isFavorite.length == 0 ? false : true);
  }, [favoriteStation, currentStationData]);
  useEffect(() => {
    const isFavorite = favoriteStation.filter((d) => {
      const compare = JSON.stringify(d);
      const current = JSON.stringify(currentStationData);
      return compare === current;
    });
    setTestButtonStatus(isFavorite.length == 0 ? false : true);
  }, [favoriteStation, currentStationData]);

  useInterval(() => {
    if (currentStationData.length == 1) {
      setNexPrePosition(0);
      return () => {};
    }
    setNexPrePosition(
      nexPrePosition + 1 == currentStationData.length ? 0 : nexPrePosition + 1
    );
  }, 2000);

  useEffect(() => {
    setNexPrePosition(0);
    getPreNextStation(currentStationData[0]);
    if (currentStationData.length == 1) return () => {};
    getPreNextStation(currentStationData[1]);
  }, [currentStationData]);

  useEffect(() => {
    if (!currentStationData[nexPrePosition]) return () => {};
    getPreNextStation(currentStationData[nexPrePosition]);
  }, [nexPrePosition]);
  const getPreNextStation = (now) => {
    const lineList = [
      "予讃線(高松-松山間)[Y]",
      "予讃線(松山-宇和島間)[U]",
      "予讃線/愛ある伊予灘線(向井原-伊予大洲間)[S]",
      "土讃線(多度津-高知間)[D]",
      "土讃線(高知-窪川間)[K]",
      "高徳線(高松-徳島間)[T]",
      "徳島線(徳島-阿波池田間)[B]",
      "鳴門線(池谷-鳴門間)[N]",
      "瀬戸大橋線(児島-宇多津間)[M]",
    ];
    let returnData;
    lineList.forEach((d) => {
      let cache = originalStationList[d].findIndex(
        (data) => data.StationNumber == now.StationNumber
      );
      if (cache != -1) {
        returnData = [
          originalStationList[d][cache - 1],
          originalStationList[d][cache + 1],
        ];
      }
    });
    if (now.Station_JP == "宇多津" && now.StationNumber == null) {
      if (returnData[1]) setPreStation(returnData[1]);
      if (returnData[0]) setNexStation(returnData[0]);
    } else {
      if (returnData[0]) setPreStation(returnData[0]);
      if (returnData[1]) setNexStation(returnData[1]);
    }
  };
  const isMatsuyama = currentStationData[0].StationNumber == "Y55";
  //const isMatsuyama = true;
  const favoliteChanger = () => {
    if (testButtonStatus) {
      const otherData = favoriteStation.filter((d) => {
        const compare = JSON.stringify(d);
        const current = JSON.stringify(currentStationData);
        return compare !== current;
      });
      AS.setItem("favoriteStation", JSON.stringify(otherData));
      setFavoriteStation(otherData);
    } else {
      let ret = favoriteStation;
      ret.push(currentStationData);
      AS.setItem("favoriteStation", JSON.stringify(ret));
      setFavoriteStation(ret);
    }
    setTestButtonStatus(!testButtonStatus);
  };

  const styleSheet = {
    外枠: {
      width: width * 0.8,
      height: ((width * 0.8) / 20) * 9,
      borderColor: "#0099CC",
      borderWidth: 1,
      backgroundColor: "white",
    },
    外枠B: {
      width: width * 0.8,
      height: ((width * 0.8) / 20) * 9,
      borderWidth: 0,
    },
    下帯: {
      position: "absolute",
      bottom: "8%",
      left: "0%",
      width: "100%",
      height: "27%",
      backgroundColor: "#0099CC",
    },
    下帯B: {
      position: "absolute",
      bottom: "0%",
      left: "0%",
      width: "100%",
      height: "26%",
      backgroundColor: "#454545",
    },
    JRStyle: {
      position: "absolute",
      top: "2%",
      left: "2%",
      fontWeight: "bold",
      fontSize: parseInt("25%"),
      color: "#0099CC",
    },
    下帯内容: {
      position: "absolute",
      bottom: "8%",
      height: "27%",
      width: "100%",
      alignItems: "center",
      flexDirection: "column",
    },
    下帯内容B: {
      position: "absolute",
      bottom: "0%",
      height: "26%",
      width: "100%",
      alignItems: "center",
      flexDirection: "column",
    },
  };

  return (
    <TouchableOpacity
      style={styleSheet[isMatsuyama ? "外枠B" : "外枠"]}
      onPress={oP}
      onLongPress={oLP}
    >
      {isMatsuyama && (
        <LottieView
          autoPlay
          loop
          style={{
            width: width * 0.8,
            height: ((width * 0.8) / 20) * 9,
            backgroundColor: "#fff",
          }}
          source={require("../../assets/StationSign.json")}
        />
      )}
      <StationNumberMaker {...{ currentStation: currentStationData }} />
      <StationNameArea
        {...{ currentStation: currentStationData, isMatsuyama }}
      />
      {isCurrentStation ? (
        <View style={{ position: "absolute", right: 0, top: 0 }}>
          <MaterialCommunityIcons
            name="crosshairs-gps"
            style={{ padding: 5 }}
            color="#0099CC"
            size={30}
          />
        </View>
      ) : (
        <TouchableOpacity
          style={{ position: "absolute", right: -15, top: -20 }}
          onPress={favoliteChanger}
        >
          <LottieDelayView progress={testButtonStatus ? 1 : 0} />
        </TouchableOpacity>
      )}

      <Text style={styleSheet.JRStyle}>JR</Text>
      <View style={styleSheet[isMatsuyama ? "下帯B" : "下帯"]} />
      <View style={styleSheet[isMatsuyama ? "下帯内容B" : "下帯内容"]}>
        <NextPreStationLine {...{ nexStation, preStation, isMatsuyama }} />
      </View>
      <AddressText {...{ currentStation: currentStationData, isMatsuyama }} />
    </TouchableOpacity>
  );
}
