import * as React from "react";
import { useState, memo } from "react";
import { View } from "react-native";
import Modal from "react-native-modal";
import CloseModalButton from "../close-modal-button";
import Nav from "./nav";
import { Item, SubItem } from "./nav";
import useNavbar from "./hooks/use-navbar";
import { SafeAreaView } from "react-native-safe-area-context";
import { useSiteSettings } from "../../providers/site";
import useGetAbsoluteUrl from "../../hooks/use-get-absolute-url";
export type Props = {
  visible: boolean;
  onClose: () => void;
  openedItems: boolean[];
  items: Item[];
  onOpenItem: (n: number) => void;
  onCloseItem: (n: number) => void;
  onOpenLink: (item: SubItem) => void;
};

function NavBar({
  visible,
  onClose,
  items,
  onCloseItem,
  onOpenItem,
  openedItems,
  onOpenLink,
}: Props) {
  return (
    <Modal
      useNativeDriver
      animationIn="fadeInDown"
      animationInTiming={150}
      animationOut="fadeOutUp"
      animationOutTiming={150}
      style={{
        margin: 0,
      }}
      isVisible={visible}
    >
      <SafeAreaView style={{ height: "100%", backgroundColor: "white" }}>
        <CloseModalButton onPress={onClose} />
        <Nav
          onOpenLink={onOpenLink}
          items={items}
          openedItems={openedItems}
          onOpenItem={onOpenItem}
          onCloseitem={onCloseItem}
        />
      </SafeAreaView>
    </Modal>
  );
}

export type NavbarProps = {
  open: boolean;
  onClose: () => void;
  onOpenLink: (item: SubItem) => void;
};

export default memo(({ onClose, onOpenLink, open }: NavbarProps) => {
  const [openedItems, setOpenedItems] = useState<boolean[]>([]);
  const {
    regions: {
      navigation: { items },
    },
  } = useSiteSettings();

  const getAbsoluteUrl = useGetAbsoluteUrl();

  function onOpenItem(index: number) {
    const newOpenedItems = [...openedItems];
    newOpenedItems[index] = true;

    setOpenedItems(newOpenedItems);
  }

  function onCloseItem(index: number) {
    const newOpenedItems = [...openedItems];
    newOpenedItems[index] = false;
    setOpenedItems(newOpenedItems);
  }
  return (
    <NavBar
      openedItems={openedItems}
      visible={open}
      items={items.map((item) => ({
        text: item.text,
        subItems: item.children.map((child) => ({
          text: child.text,
          link: getAbsoluteUrl(child.link || ""),
        })),
      }))}
      onOpenLink={(item) => {
        onClose();
        onOpenLink(item);
      }}
      onClose={onClose}
      onCloseItem={onCloseItem}
      onOpenItem={onOpenItem}
    />
  );
});
