import React, { useState, useEffect } from "react";
import {
  View,
  Linking,
  BackHandler,
  Platform,
  useWindowDimensions,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import ActionSheet, { SheetManager } from "react-native-actions-sheet";
import Sign from "../../components/駅名表/Sign";

import { getPDFViewURL } from "../../lib/getPdfViewURL";
import { useBusAndTrainData } from "../../stateBox/useBusAndTrainData";
import { AS } from "../../storageControl";
import { StationMapButton } from "./StationDeteilView/StationMapButton";
import { TrainBusButton } from "./StationDeteilView/TrainBusButton";
import { 駅構内図 } from "./StationDeteilView/StationInsideMapButton";
import { WebSiteButton } from "./StationDeteilView/WebSiteButton";
import { StationTimeTableButton } from "./StationDeteilView/StationTimeTableButton";
import { StationTrainPositionButton } from "./StationDeteilView/StationTrainPositionButton";
import { StationDiagramButton } from "./StationDeteilView/StationDiagramButton";
import { useTrainMenu } from "@/stateBox/useTrainMenu";

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

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

  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: width * 0.1 }}>
                <Sign
                  stationID={currentStation[0].StationNumber}
                  oP={() => {
                    usePDFView == "true"
                      ? Linking.openURL(currentStation[0].StationTimeTable)
                      : navigate("howto", {
                          info,
                          goTo,
                          useShow,
                        });
                    onExit();
                  }}
                  oLP={() =>
                    Linking.openURL(currentStation[0].StationTimeTable)
                  }
                />
              </View>
              <View style={{ flexDirection: "row" }}>
                <StationTrainPositionButton
                  stationNumber={currentStation[0].StationNumber}
                  onExit={onExit}
                  navigate={navigate}
                />
                {currentStation[0].JrHpUrl &&
                  currentStation[0].StationNumber != "M12" && (
                    <駅構内図 //児島例外/
                      navigate={navigate}
                      goTo={goTo}
                      useShow={useShow}
                      address={currentStation[0].JrHpUrl}
                      onExit={onExit}
                    />
                  )}
              </View>
              <View style={{ flexDirection: "row" }}>
                {!currentStation[0].JrHpUrl || (
                  <WebSiteButton
                    navigate={navigate}
                    info={currentStation[0].JrHpUrl}
                    goTo={goTo}
                    useShow={useShow}
                    onExit={onExit}
                  />
                )}
                {updatePermission &&<StationDiagramButton
                    navigate={navigate}
                    onExit={onExit}
                    currentStation={currentStation}
                  />}
                {!currentStation[0].StationTimeTable || (
                  <StationTimeTableButton
                    info={info}
                    address={currentStation[0].StationTimeTable}
                    usePDFView={usePDFView}
                    navigate={navigate}
                    onExit={onExit}
                    goTo={goTo}
                    useShow={useShow}
                  />
                )}
                <StationMapButton
                  stationMap={
                    currentStation[0].StationMap ||
                    `https://www.google.co.jp/maps/place/${currentStation[0].lat},${currentStation[0].lng}`
                  }
                />
                {!trainBus || (
                  <TrainBusButton
                    address={trainBus.address}
                    press={() => {
                      navigate("howto", {
                        info: trainBus.address,
                        goTo,
                        useShow,
                      });
                      onExit();
                    }}
                  />
                )}
              </View>
            </>
          )}
        </View>
      </View>
    </ActionSheet>
  );
};

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