import React, { useState } from 'react'
import Link from 'next/link';
import classnames from 'classnames';

import Button from './Button';
import { MenuItem } from './Navbar'

interface Props {
    item: MenuItem;
}

export default function Dropdown(props: Props) {
    const { item } = props;
    const [isOpen, setIsOpen] = useState<boolean>(false);
    const menuItems = item?.children ? item.children : [];
    const lastIndex = menuItems.length - 1;
    const itemId = item.id;

    const toggle = () => {
        setIsOpen(old => !old);
    }

    const transClass = isOpen
        ?
        "flex"
        :
        "hidden";
    
    function isLastItem (currentItem: MenuItem) {
        return lastIndex == menuItems.indexOf(currentItem)
    }

    function isSecondItem (currentItem: MenuItem) {
        return 1 == menuItems.indexOf(currentItem)
    }

    return (
        <>
            <div className="relative">
                <Button
                    className="hover:text-britton-light font-semibold text-lg"
                    onClick={toggle}
                >{item.title}</Button>
                <div className={`absolute top-8 z-11 w-[150px] flex flex-col bg-stone-300 text-sm rounded-md ${transClass}`}>
                    {
                        menuItems.map(item =>
                            <>
                                <Link
                                    key={item.id}
                                    className={classnames(
                                        "hover:text-britton-neutral text-center px-2 py-1",
                                        {
                                            "hover:bg-britton-newblue" : itemId == 'employers',
                                            "hover:bg-britton-medium" : itemId != 'employers'
                                        }
                                    )}
                                    href={item?.route || ''}
                                    onClick={toggle}
                                >
                                    {item.title}
                                </Link>
                                <div className={classnames(
                                        "h-px bg-britton-accent mx-2",
                                        {"hidden" : isLastItem(item)}
                                    )}
                                />
                            </>
                        )
                    }
                </div>
            </div>
            {
                isOpen
                    ?
                    <div
                        className="fixed top-0 right-0 bottom-0 left-0 z-11 bg-britton-dark/40"
                        onClick={toggle}
                    ></div>
                    :
                    <></>
            }
        </>
    )
}