import { Fragment, ReactNode } from 'react';
import { classNamesTailwind } from '../../utils/theme';
import { NavigationItem } from '../NavigationItem';
import { Menu as Dropdown, Transition } from '@headlessui/react';

export interface MenuProps {
    items: NavigationItem[];
    className?: string;
    classNameItem?: string;
    close: () => void;
    renderItem: ({ item, close, mobile }: { item: NavigationItem; close: () => void; mobile: boolean }) => ReactNode;
}

const renderMenuItem = (
    item: NavigationItem,
    close: () => void,
    renderItem: ({ item, close, mobile }: { item: NavigationItem; close: () => void; mobile: boolean }) => ReactNode
) => {
    if (item.items && item.items.length > 0) {
        return (
            <Dropdown as="div" className="relative">
                {({ open }) => (
                    <>
                        <Dropdown.Button>{renderItem({ item, close, mobile: false })}</Dropdown.Button>
                        <Transition
                            show={open}
                            as={Fragment}
                            enter="transition ease-out duration-100"
                            enterFrom="transform opacity-0 scale-95"
                            enterTo="transform opacity-100 scale-100"
                            leave="transition ease-in duration-75"
                            leaveFrom="transform opacity-100 scale-100"
                            leaveTo="transform opacity-0 scale-95"
                        >
                            <Dropdown.Items className="absolute right-0 mt-2 w-56 origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow ring-opacity-5 focus:outline-none">
                                {item.items.map((item) => renderItem({ item, close, mobile: false }))}
                            </Dropdown.Items>
                        </Transition>
                    </>
                )}
            </Dropdown>
        );
    }

    return renderItem({ item, close, mobile: false });
};

const Menu = ({ className, items, classNameItem, renderItem, close }: MenuProps) => {
    return (
        <nav>
            <ul className={classNamesTailwind('hidden md:flex list-none', className)}>
                {items.map((item) => {
                    // const last = index === items.length - 1;

                    return (
                        <li key={item.id} className={classNameItem}>
                            {renderMenuItem(item, close, renderItem)}
                        </li>
                    );
                })}
            </ul>
        </nav>
    );
};

export default Menu;
