import React, { useState, useEffect } from "react";
import {
  View,
  Linking,
  Text,
  TouchableOpacity,
  BackHandler,
  Platform,
} from "react-native";
import AutoHeightImage from "react-native-auto-height-image";
import { FontAwesome, Foundation, Ionicons } from "@expo/vector-icons";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import ActionSheet, { SheetManager } from "react-native-actions-sheet";
import Sign from "../../components/駅名表/Sign";

import { TicketBox } from "../atom/TicketBox";
import { widthPercentageToDP as wp } from "react-native-responsive-screen";
import { getPDFViewURL } from "../../lib/getPdfViewURL";
import { useBusAndTrainData } from "../../stateBox/useBusAndTrainData";
import { AS } from "../../storageControl";

export const StationDeteilView = (props) => {
  if (!props.payload) return <></>;
  const {
    currentStation,
    navigate,
    onExit,
    goTo,
    useShow,
  } = props.payload;
  const { busAndTrainData } = useBusAndTrainData();
  const [trainBus, setTrainBus] = useState();

  useEffect(() => {
    if (!currentStation) return () => {};
    const data = busAndTrainData.filter((d) => {
      return d.name === currentStation[0].Station_JP;
    });
    if (data.length == 0) {
      setTrainBus();
    }
    setTrainBus(data[0]);
  }, [currentStation]);

  const [usePDFView, setUsePDFView] = useState(undefined);
  useEffect(() => {
    AS.getItem("usePDFView").then(setUsePDFView);
  }, []);
  const info =
    currentStation &&
    (currentStation[0].StationTimeTable.match(".pdf")
      ? getPDFViewURL(currentStation[0].StationTimeTable)
      : currentStation[0].StationTimeTable);
  const insets = useSafeAreaInsets();
  return (
    <ActionSheet
      gestureEnabled
      CustomHeaderComponent={<></>}
      isModal={Platform.OS == "ios"}
      containerStyle={
        Platform.OS == "android"
          ? {
              paddingBottom: insets.bottom,
            }
          : {}
      }
      useBottomSafeAreaPadding={Platform.OS == "android"}
    >
      <Handler />
      <View
        key={currentStation}
        style={{
          backgroundColor: "white",
          borderTopRadius: 5,
          borderColor: "dark",
          borderWidth: 1,
        }}
      >
        <View style={{ height: 26, width: "100%" }}>
          <View
            style={{
              height: 6,
              width: 45,
              borderRadius: 100,
              backgroundColor: "#f0f0f0",
              marginVertical: 10,
              alignSelf: "center",
            }}
          />
        </View>
        <View>
          {currentStation && (
            <View
              style={{
                margin: 10,
                marginHorizontal: wp("10%"),
              }}
            >
              <Sign
                currentStation={currentStation}
                oP={() => {
                  usePDFView == "true"
                    ? Linking.openURL(currentStation[0].StationTimeTable)
                    : navigate("howto", {
                        info,
                        goTo,
                        useShow,
                      });
                  onExit();
                }}
                oLP={() => Linking.openURL(currentStation[0].StationTimeTable)}
              />
            </View>
          )}
          {currentStation &&
            currentStation[0].JrHpUrl &&
            currentStation[0].StationNumber != "M12" && (
              <駅構内図 //高松/阿波池田&後免&須崎kounai.png児島例外/
                oP={() => {
                  navigate("howto", {
                    info:
                      currentStation[0].JrHpUrl.replace("/index.html", "/") +
                      "/kounai_map.html",
                    goTo,
                    useShow,
                  });
                  onExit();
                }}
                oLP={() => {
                  Linking.openURL(
                    currentStation[0].JrHpUrl.replace("/index.html", "/") +
                      "/kounai_map.html"
                  );
                }}
                uri={currentStation[0].JrHpUrl.replace("/index.html", "/")}
              />
            )}
          {currentStation && (
            <View style={{ flexDirection: "row" }}>
              {!currentStation[0].JrHpUrl || (
                <TicketBox
                  backgroundColor={"#AD7FA8"}
                  icon={<Foundation name="web" color="white" size={50} />}
                  flex={1}
                  onPressButton={() => {
                    navigate("howto", {
                      info: currentStation[0].JrHpUrl,

                      goTo,
                      useShow,
                    });
                    onExit();
                  }}
                  onLongPressButton={() =>
                    Linking.openURL(currentStation[0].JrHpUrl)
                  }
                >
                  web
                </TicketBox>
              )}
              {!currentStation[0].StationTimeTable || (
                <TicketBox
                  backgroundColor={"#8F5902"}
                  icon={<FontAwesome name="table" color="white" size={50} />}
                  flex={1}
                  onPressButton={() => {
                    usePDFView == "true"
                      ? Linking.openURL(currentStation[0].StationTimeTable)
                      : navigate("howto", {
                          info,

                          goTo,
                          useShow,
                        });
                    onExit();
                  }}
                  onLongPressButton={() =>
                    Linking.openURL(currentStation[0].StationTimeTable)
                  }
                >
                  時刻表
                </TicketBox>
              )}
              {!currentStation[0].StationMap || (
                <TicketBox
                  backgroundColor={"#888A85"}
                  icon={<Ionicons name="map" color="white" size={50} />}
                  flex={1}
                  onPressButton={() =>
                    Linking.openURL(currentStation[0].StationMap)
                  }
                >
                  Map
                </TicketBox>
              )}
              {!trainBus || (
                <TicketBox
                  backgroundColor={"#CE5C00"}
                  icon={<Ionicons name="bus" color="white" size={50} />}
                  flex={1}
                  onPressButton={() => {
                    navigate("howto", {
                      info: trainBus.address,

                      goTo,
                      useShow,
                    });
                    onExit();
                  }}
                  onLongPressButton={() => Linking.openURL(trainBus.address)}
                >
                  並行バス
                </TicketBox>
              )}
            </View>
          )}
        </View>
      </View>
    </ActionSheet>
  );
};


const 駅構内図 = (props) => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <TouchableOpacity
        style={{
          height: 50,
          backgroundColor: "#888A85",
          flexDirection: "column",
          alignContent: "center",
          alignItems: "center",
          margin: 2,
        }}
        onPress={props.oP}
        onLongPress={props.oLP}
        //onPress={() => setOpen(!open)}
      >
        <View style={{ flex: 1 }} />
        <Text
          style={{
            color: "white",
            textAlign: "center",
            textAlignVertical: "center",
            flex: 1,
          }}
        >
          {open ? "駅構内図を非表示" : "駅構内図を表示"}
        </Text>
        <View style={{ flex: 1 }} />
      </TouchableOpacity>
      <View>
        {open && (
          <>
            <AutoHeightImage
              source={{ uri: props.uri + "images/kounai.gif" }}
              resizeMode="contain"
              width={wp("100%")}
            />
            <AutoHeightImage
              source={{ uri: props.uri + "images/kounai.png" }}
              resizeMode="contain"
              width={wp("100%")}
            />
            <AutoHeightImage
              source={{ uri: props.uri + "images/kounai_1f.gif" }}
              resizeMode="contain"
              width={wp("100%")}
            />
            <AutoHeightImage
              source={{ uri: props.uri + "images/kounai_2f.png" }}
              resizeMode="contain"
              width={wp("100%")}
            />
          </>
        )}
      </View>
    </>
  );
};

const Handler = () => {
  useEffect(() => {
    const backAction = () => {
      SheetManager.hide("StationDetailView");
      return true;
    };
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );
    return () => backHandler.remove();
  }, []);
  return <></>;
};