import { router } from "expo-router";
import { useCallback, useEffect } from "react";
import { IoniconsType } from "../../lib/types";
import { ListItem, ListView } from "./ListView";

type RedirectToRoute = {
  route: string;
};
type OnPressAction = {
  onPress: () => void;
};

export type MenuItemData = {
  id: string;
  title: string;
  icon: IoniconsType;
  isDisabled?: boolean;
} & (RedirectToRoute | OnPressAction);

export function MenuSection({
  title,
  items,
  pressedItem,
  setPressedItem,
}: {
  title: string;
  items: MenuItemData[];
  pressedItem: MenuItemData | null;
  setPressedItem: React.Dispatch<
    React.SetStateAction<MenuItemData | null>
  >;
}) {
  const handleItemPress = useCallback(
    (item: MenuItemData) => {
      setPressedItem((prev: MenuItemData | null) => {
        if (prev !== null) return prev;
        return item;
      });
    },
    [setPressedItem]
  );

  useEffect(() => {
    if (!pressedItem || !items.find((item) => item.id === pressedItem.id))
      return;

    if ("route" in pressedItem) {
      router.push(pressedItem.route);
    } else if ("onPress" in pressedItem) {
      pressedItem.onPress();
    }

    const clear = setTimeout(() => setPressedItem(null), 1000);
    return () => {
      clearTimeout(clear);
    };
  }, [pressedItem]);

  return (
    <ListView title={title}>
      {items.map((item, index) => (
        <ListItem
          key={`${title}-${index}`}
          title={item.title}
          icon={item.icon}
          isDisabled={item.isDisabled || pressedItem !== null}
          onPress={() => handleItemPress(item)}
        />
      ))}
    </ListView>
  );
}
