import React, { useEffect, useRef } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  Platform,
  BackHandler,
} from "react-native";
import ActionSheet, { SheetManager } from "react-native-actions-sheet";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTrainMenu } from "../../stateBox/useTrainMenu";
import { useCurrentTrain } from "../../stateBox/useCurrentTrain";
import lineColorList from "../../assets/originData/lineColorList";
import { stationIDPair, lineListPair } from "../../lib/getStationList";
import { useThemeColors } from "@/lib/theme";
import { useSheetMaxHeight } from "./useSheetMaxHeight";

export const TrainMenuLineSelector = () => {
  const {
    selectedLine,
    setSelectedLine,
    mapsStationData: stationData,
  } = useTrainMenu();
  const { webview } = useCurrentTrain();
  const actionSheetRef = useRef(null);
  const insets = useSafeAreaInsets();
  const platformIs = Platform.OS == "android";
  const { colors, fixed } = useThemeColors();
  const maxHeight = useSheetMaxHeight();
  return (
    <ActionSheet
      gestureEnabled
      CustomHeaderComponent={<></>}
      ref={actionSheetRef}
      isModal={Platform.OS === "ios" && !Platform.isPad}
      containerStyle={{
        ...(platformIs ? { paddingBottom: insets.bottom } : {}),
        ...(maxHeight != null ? { maxHeight } : {}),
      }}
      useBottomSafeAreaPadding={platformIs}
    >
      <Handler />
      <View style={{ height: 26, width: "100%", backgroundColor: colors.sheetBackground }}>
        <View
          style={{
            height: 6,
            width: 45,
            borderRadius: 100,
            backgroundColor: colors.borderLight,
            marginVertical: 10,
            alignSelf: "center",
          }}
        />
      </View>
      {Object.keys(stationData).map((d) => (
        <TouchableOpacity
          style={{
            flexDirection: "row",
            backgroundColor: selectedLine == d ? "#0099CC33" : colors.surface,
          }}
          onPress={() => {
            SheetManager.hide("TrainMenuLineSelector");
            const s = selectedLine == d ? undefined : d;
            if (!s) return;
            setSelectedLine(s);
            Object.keys(stationData).forEach((data, indexBase) => {
              stationData[data].forEach((D, index) => {
                if (!D.StationMap) return null;
                if (s && s != data) return;
                const latlng = D.StationMap.replace(
                  "https://www.google.co.jp/maps/place/",
                  ""
                ).split(",");
                if (latlng.length == 0) return null;
                if (index == 0) {
                  webview.current
                    ?.injectJavaScript(`MoveDisplayStation('${data}_${D.MyStation}_${D.Station_JP}');
                      document.getElementById("disp").insertAdjacentHTML("afterbegin", "<div />");`);
                }
              });
            });
          }}
          key={d+"TrainMenuLineSelector"}
        >
          <View
            style={{
              width: 35,
              position: "relative",
              marginHorizontal: 15,
              flexDirection: "row",
              height: "101%",
            }}
          >
            <View
              style={{
                backgroundColor: lineColorList[stationIDPair[d]],
                flex: 1,
              }}
            >
              <View style={{ flex: 1 }} />
              <Text
                style={{
                  color: fixed.textOnPrimary,
                  textAlign: "center",
                  fontSize: 12,
                  fontWeight: "bold",
                }}
              >
                {stationIDPair[d]}
              </Text>
              <View style={{ flex: 1 }} />
            </View>
          </View>

          <View
            style={{
              padding: 8,
              flexDirection: "row",
              borderBottomWidth: 1,
              borderBottomColor: colors.borderLight,
              flex: 1,
              alignContent: "center",
              alignItems: "center",
            }}
          >
            <Text style={{ fontSize: 20, color: colors.text }}>
              {lineListPair[stationIDPair[d]]}
            </Text>
            <View style={{ flex: 1 }} />
          </View>
        </TouchableOpacity>
      ))}
    </ActionSheet>
  );
};
const Handler = () => {
  useEffect(() => {
    const backAction = () => {
      SheetManager.hide("TrainMenuLineSelector");
      return true;
    };
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );
    return () => backHandler.remove();
  }, []);
  return <></>;
};
