import { useActionSheet, ActionSheetOptions } from "@expo/react-native-action-sheet";
import { useThemeColor } from "../lib/hooks/use-theme-color";
import { useColorScheme } from "../lib/hooks/use-color-scheme";
import { Platform, BackHandler } from "react-native";

export function useThemedActionSheet() {
  const { showActionSheetWithOptions } = useActionSheet();
  
  const bgColor = useThemeColor("card");
  const textColor = useThemeColor("text");
  const notifColor = useThemeColor("notification");

  const colorScheme = useColorScheme();
  const rippleColor = colorScheme === "dark" ? "#3a3b3d" : "rgba(255, 255, 255)";

  const show = (options: ActionSheetOptions, callback: (index?: number) => void) => {
    if (Platform.OS === "android") {
      let backHandler: any;

      const wrappedCallback = (selectedIndex?: number) => {
        if (backHandler) {
          backHandler.remove();
          backHandler = null;
        }
        callback(selectedIndex);
      };

      if (options.cancelButtonIndex == null) {
        backHandler = BackHandler.addEventListener("hardwareBackPress", () => true);
      }

      showActionSheetWithOptions(
        {
          ...options,
          titleTextStyle: { color: textColor + "99" },
          textStyle: { color: textColor },
          tintColor: textColor,
          containerStyle: { backgroundColor: bgColor },
          cancelButtonIndex: options.cancelButtonIndex,
          destructiveColor: notifColor,
          rippleColor
        },
        wrappedCallback
      );
    } else {
      showActionSheetWithOptions(options, callback);
    }
  };

  return { showActionSheetWithOptions: show };
}