import React, { Component, useRef, useState, useEffect } from "react";
import {
  StatusBar,
  View,
  LayoutAnimation,
  ScrollView,
  Linking,
  Text,
  TouchableOpacity,
} from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import LottieView from "lottie-react-native";
import { useInterval } from "../../lib/useInterval";
import { AS } from "../../storageControl";

export default function Sign(props) {
  const { currentStation, originalStationList, oP } = props;
  const [nexPrePosition, setNexPrePosition] = useState(0);

  const [preStation, setPreStation] = useState();
  const [nexStation, setNexStation] = useState();
  const [testButtonStatus, setTestButtonStatus] = useState(false);
  const [favoriteStation, setFavoriteStation] = useState([]);

  useEffect(() => {
    AS.getItem("favoriteStation")
      .then((d) => {
        console.log(d);
        const returnData = JSON.parse(d);
        console.log(returnData);
        setFavoriteStation(returnData);
      })
      .catch((d) => console.log(d));
  }, []);
  useEffect(() => {
    const isFavorite = favoriteStation.filter((d) => {
      const compare = JSON.stringify(d);
      const current = JSON.stringify(currentStation);
      if (compare === current) {
        return true;
      } else {
        return false;
      }
    });
    console.log(isFavorite.length);
    setTestButtonStatus(isFavorite.length != 0);
  }, [favoriteStation, currentStation]);

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

  useEffect(() => {
    setNexPrePosition(0);
    getPreNextStation(currentStation[0]);
  }, [currentStation]);

  useEffect(() => {
    if (!currentStation[nexPrePosition]) return () => {};
    getPreNextStation(currentStation[nexPrePosition]);
  }, [nexPrePosition]);
  const getPreNextStation = (now) => {
    const lineList = [
      "予讃線",
      "松宇線",
      "伊予灘線",
      "土讃線",
      "窪川線",
      "高徳線",
      "徳島線",
      "鳴門線",
      "瀬戸大橋線",
    ];
    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],
        ];
      }
    });
    setPreStation(returnData[0]);
    setNexStation(returnData[1]);
  };
  const lottieRef = useRef();
  return (
    <TouchableOpacity style={styleSheet.外枠} onPress={oP}>
      <StationNumberMaker currentStation={currentStation} />
      <StationNameArea currentStation={currentStation} />
      <TouchableOpacity
        style={{ position: "absolute", right: -15, top: -20 }}
        onPress={() => {
          if (testButtonStatus) {
            lottieRef.current.play(35, 7);
            const otherData = favoriteStation.filter((d) => {
              const compare = JSON.stringify(d);
              const current = JSON.stringify(currentStation);
              if (compare !== current) {
                return true;
              } else {
                return false;
              }
            });
            AS.setItem("favoriteStation", JSON.stringify(otherData));
          } else {
            lottieRef.current.play(7, 35);
            let ret = favoriteStation;
            console.log(currentStation);
            ret.push(currentStation);
            AS.setItem("favoriteStation", JSON.stringify(ret));
          }
          setTestButtonStatus(!testButtonStatus);
        }}
      >
        <LottieView
          progress={testButtonStatus ? 1 : 0}
          speed={1.4}
          style={{ width: 80, height: 80 }}
          source={require("../../assets/939-star.json")}
          ref={lottieRef}
          loop={false}
        />
      </TouchableOpacity>

      <Text style={styleSheet.JRStyle}>JR</Text>
      <View style={styleSheet.下帯} />
      <View style={styleSheet.下帯内容}>
        <NexPreStationLine preStation={preStation} nexStation={nexStation} />
      </View>
    </TouchableOpacity>
  );
}

const NexPreStationLine = ({ nexStation, preStation }) => {
  return (
    <View style={styleSheet.下枠フレーム}>
      <View style={styleSheet.下枠フレーム}>
        {preStation && (
          <>
            <Text style={styleSheet.下枠左右マーク}>◀</Text>
            {preStation.StationNumber && (
              <View style={styleSheet.下枠駅ナンバー}>
                <View style={{ flex: 1 }} />
                <Text
                  style={{
                    fontSize: parseInt("10%"),
                    color: "white",
                  }}
                >
                  {preStation.StationNumber}
                </Text>
                <View style={{ flex: 1 }} />
              </View>
            )}
            <StationName
              stringData={preStation}
              ss={{ flex: 1, alignItems: "flex-start" }}
            />
          </>
        )}
      </View>
      <View style={styleSheet.下枠フレーム}>
        {nexStation && (
          <>
            <StationName
              stringData={nexStation}
              ss={{ flex: 1, alignItems: "flex-end" }}
            />
            {nexStation.StationNumber && (
              <View style={styleSheet.下枠駅ナンバー}>
                <View style={{ flex: 1 }} />
                <Text style={{ fontSize: parseInt("10%"), color: "white" }}>
                  {nexStation.StationNumber}
                </Text>
                <View style={{ flex: 1 }} />
              </View>
            )}
            <Text style={styleSheet.下枠左右マーク}>▶</Text>
          </>
        )}
      </View>
    </View>
  );
};

const StationNumberMaker = (props) => {
  const getTop = (array, index) => {
    if (array.length == 1) return 20;
    else if (index == 0) return 5;
    else if (index == 1) return 35;
    else return 20;
  };
  return props.currentStation
    .filter((d) => (d.StationNumber ? true : false))
    .map((d, index, array) => (
      <View
        style={{
          position: "absolute",
          alignContent: "center",
          alignItems: "center",
          top: getTop(array, index) + "%",
          right: "10%",
          width: wp("10%"),
          height: wp("10%"),
          borderColor: "#2E94BB",
          borderWidth: parseInt("2%"),
          borderRadius: parseInt("100%"),
        }}
      >
        <View style={{ flex: 1 }} />
        <Text style={{ fontSize: parseInt("20%") }}>{d.StationNumber}</Text>
        <View style={{ flex: 1 }} />
      </View>
    ));
};

const StationNameArea = (props) => {
  const { currentStation } = props;
  return (
    <View style={styleSheet.stationNameAreaOverWrap}>
      <View style={{ flex: 1 }} />
      <View style={{ alignItems: "center" }}>
        {/* <Text style={{fontWeight:"bold",fontSize:parseInt("15%"),color:"#005170"}}>{stationName.今.LineName}</Text>  */}
        <Text style={styleSheet.Station_JP}>
          {currentStation[0].Station_JP}
        </Text>
        <Text style={styleSheet.Station_EN}>
          {currentStation[0].Station_EN}
        </Text>
      </View>
      <View style={{ flex: 1 }} />
    </View>
  );
};

const StationName = (props) => {
  const { stringData, ss } = props;
  return (
    <View style={ss}>
      <Text style={styleSheet.下枠駅名}>{stringData.Station_JP}</Text>
      <Text style={styleSheet.下枠駅名}>{stringData.Station_EN}</Text>
    </View>
  );
};

const styleSheet = {
  外枠: {
    width: wp("80%"),
    height: (wp("80%") / 20) * 9,
    borderColor: "#2E94BB",
    borderWidth: 1,
    margin: 10,
    marginHorizontal: wp("10%"),
    backgroundColor: "white",
  },
  下帯: {
    position: "absolute",
    bottom: "0%",
    left: "0%",
    width: "100%",
    height: "30%",
    backgroundColor: "#2E94BB",
  },
  JRStyle: {
    position: "absolute",
    top: "2%",
    left: "2%",
    fontWeight: "bold",
    fontSize: parseInt("30%"),
    color: "#2E94BB",
  },
  stationNameAreaOverWrap: {
    position: "absolute",
    top: "10%",
    alignContent: "center",
    flexDirection: "row",
  },
  Station_JP: {
    fontWeight: "bold",
    fontSize: parseInt("40%"),
    color: "#005170",
  },
  Station_EN: {
    fontWeight: "bold",
    fontSize: parseInt("15%"),
    color: "#005170",
  },
  下帯内容: {
    position: "absolute",
    bottom: "0%",
    height: "30%",
    width: "100%",
    alignItems: "center",
    flexDirection: "column",
  },
  下枠フレーム: {
    flex: 1,
    flexDirection: "row",
    alignContent: "center",
  },
  下枠左右マーク: {
    fontWeight: "bold",
    fontSize: parseInt("20%"),
    color: "white",
    paddingHorizontal: 10,
    textAlignVertical: "center",
  },
  下枠駅ナンバー: {
    alignContent: "center",
    alignItems: "center",
    width: wp("8%"),
    height: wp("8%"),
    margin: wp("1%"),
    borderColor: "white",
    borderWidth: parseInt("2%"),
    borderRadius: parseInt("100%"),
  },
  下枠駅名: {
    fontWeight: "bold",
    fontSize: parseInt("15%"),
    color: "white",
    flex: 1,
    textAlignVertical: "center",
  },
};
