import React, { useState } from "react";
import Typography from "../typography/typography";
import Avatar from "../avatar/avatar";
import Menu, { MenuProps, ItemProps, Item } from "./menu";
import UserProfile from "../user-profile/user-profile";
import SearchBar from "./search-bar";
import { Icon } from "../icon";

type MenuItemType = (MenuProps | ItemProps) & {
    type?: "menu" | "item";
};

const menuSubItems: MenuItemType[] = [
    { id: "overview", title: "Overview", icon: "activity" },
    {
        id: "notifications",
        title: "Notifications",
        icon: "notification-box",
    },
    { id: "analytics", title: "Analytics", icon: "bar-line-chart" },
    { id: "saved-reports", title: "Saved reports", icon: "star-01" },
    {
        id: "scheduled-reports",
        title: "Scheduled reports",
        icon: "clock-fast-forward",
    },
    { id: "user-reports", title: "User reports", icon: "user-square" },
    {
        id: "manage-notifications",
        title: "Manage Notifications",
        icon: "settings-03",
    },
];

const menuItems: MenuItemType[] = [
    {
        id: "home",
        title: "Home",
        icon: "home-line",
        items: menuSubItems,
        type: "menu",
    },
    {
        id: "opportunities",
        title: "Opportunities",
        icon: "lightbulb-03",
        items: menuSubItems,
        type: "menu",
    },
    {
        id: "templates",
        title: "Templates",
        icon: "file-07",
        items: menuSubItems,
        type: "menu",
    },
    {
        id: "reports",
        title: "Reports",
        icon: "pie-chart-03",
        items: menuSubItems,
        type: "menu",
    },
    {
        id: "insights",
        title: "Insights",
        icon: "eye",
        items: menuSubItems,
        type: "menu",
    },
    {
        id: "enablement",
        title: "Enablement",
        icon: "check-circle",
        items: menuSubItems,
        type: "menu",
    },
];

const bottomMenuItems: MenuItemType[] = [
    {
        id: "support",
        title: "Support",
        icon: "life-buoy-01",
    },
    {
        id: "company-settings",
        title: "Company Settings",
        icon: "settings-01",
    },
];

export const SideBar = () => {
    const [openUserSettings, setOpenUserSettings] = useState(false);
    const [selectedPath, setSelectedPath] = useState<string[]>([]);
    const [selectedItemId, selectedSubItemId] = selectedPath;
    const renderMenuItems = (menuItems: MenuItemType[]) =>
        menuItems.map(({ type, id, onClick, ...props }) => {
            const isOpenAlready = selectedItemId === id;
            const onClickHandler: React.MouseEventHandler<HTMLDivElement> =
                event => {
                    setSelectedPath(isOpenAlready ? [] : [id]);
                    onClick?.(event);
                };
            return type === "menu" ? (
                <Menu
                    key={id}
                    id={id}
                    open={isOpenAlready}
                    onClick={onClickHandler}
                    {...props}
                    items={((props as MenuProps)?.items ?? []).map(
                        ({
                            id: itemId,
                            onClick: onItemClick,
                            ...restItemProps
                        }) => ({
                            id: itemId,
                            onClick: event => {
                                setSelectedPath([id, itemId]);
                                onItemClick?.(event);
                            },
                            selected: itemId === selectedSubItemId,
                            ...restItemProps,
                        })
                    )}
                />
            ) : (
                <Item
                    key={id}
                    selected={isOpenAlready}
                    onClick={onClickHandler}
                    {...props}
                />
            );
        });
    const renderIconMenuItems = (menuItems: MenuItemType[]) =>
        menuItems.map(({ id, onClick, icon }) => {
            const isOpenAlready = selectedItemId === id;
            const onClickHandler: React.MouseEventHandler<HTMLDivElement> =
                event => {
                    setSelectedPath(isOpenAlready ? [] : [id]);
                    onClick?.(event);
                };
            return icon ? (
                <div
                    onClick={onClickHandler}
                    className={`p-3.5 cursor-pointer hover:bg-gray-50 rounded-md ${
                        isOpenAlready ? "bg-gray-50" : ""
                    }`}
                >
                    <Icon name={icon} size={20} color="gray-500" />
                </div>
            ) : null;
        });

    const selectedMenu = [...menuItems, ...bottomMenuItems].find(
        ({ id, type = "item" }) => id === selectedItemId && type === "menu"
    ) as MenuProps;
    const userProfileRightIcon = openUserSettings ? (
        <Icon name="x-close" size={20} color="gray-500" />
    ) : (
        <Icon name="chevron-right" size={20} color="gray-500" />
    );

    const sideBarClasses =
        "h-full border border-gray-200 bg-white px-4 pt-6 pb-4 overflow-auto";
    return (
        <div className="relative h-full w-fit">
            {/* DESKTOP VIEW */}
            <div
                className={`hidden xl:flex flex-col w-[312px] ${sideBarClasses}`}
            >
                <img
                    src="/images/trinity-logo.svg"
                    className="w-32 h-8 mx-3 my-4"
                />
                <SearchBar />
                <div className="flex-grow">{renderMenuItems(menuItems)}</div>
                <div>{renderMenuItems(bottomMenuItems)}</div>
                <div className="my-4 border-t border-t-gray-100 cursor-pointer" />
                <div
                    className="flex p-2 hover:bg-gray-50 cursor-pointer rounded-md"
                    onClick={() => setOpenUserSettings(prev => !prev)}
                >
                    <UserProfile
                        name="Siva Vepada"
                        subTitle="Developer"
                        avatar="https://avatars.githubusercontent.com/u/28987707?s=96&v=4"
                    />
                    <div>{userProfileRightIcon}</div>
                </div>
            </div>
            {/* DESKTOP VIEW */}
            {/* TABLET VIEW */}
            <div className={`xl:hidden flex flex-row h-full`}>
                <div className={`flex flex-col items-center ${sideBarClasses}`}>
                    <img
                        src="/images/trinity-logo-icon.svg"
                        className="w-8 my-4"
                    />
                    <div className="flex flex-col flex-grow mt-2">
                        {renderIconMenuItems(menuItems)}
                    </div>
                    <div className="mb-6">
                        {renderIconMenuItems(bottomMenuItems)}
                    </div>
                    <div
                        className="flex justify-center cursor-pointer"
                        onClick={() => setOpenUserSettings(prev => !prev)}
                    >
                        <Avatar
                            src="https://avatars.githubusercontent.com/u/28987707?s=96&v=4"
                            name="Siva Vepada"
                        />
                    </div>
                </div>
                {selectedMenu && (
                    <div className="w-72 px-4 py-6 flex flex-col border-r border-y border-gray-200">
                        <Typography className="text-gray-900 mb-4">
                            Dashboard
                        </Typography>
                        <div className="flex-grow">
                            {selectedMenu.items?.map(
                                ({ id, onClick, ...restProps }) => {
                                    const isSelected = id === selectedSubItemId;
                                    return (
                                        <Item
                                            id={id}
                                            key={id}
                                            onClick={event => {
                                                setSelectedPath(
                                                    isSelected
                                                        ? []
                                                        : [selectedMenu.id, id]
                                                );
                                                onClick?.(event);
                                            }}
                                            selected={isSelected}
                                            {...restProps}
                                        />
                                    );
                                }
                            )}
                        </div>

                        <div
                            className="flex py-2 hover:bg-gray-50 cursor-pointer rounded-md"
                            onClick={() => setOpenUserSettings(prev => !prev)}
                        >
                            <UserProfile
                                name="Siva Vepada"
                                subTitle="Developer"
                            />
                            <div>{userProfileRightIcon}</div>
                        </div>
                    </div>
                )}
            </div>
            {/* TABLET VIEW */}
            {openUserSettings && (
                <div className="absolute -right-[264px] bottom-12 z-20 w-[256px] bg-white rounded-md shadow-lg border border-gray-100">
                    <Item title="My Settings" icon="settings-01" />
                    <Item
                        title="Company"
                        icon="message-smile-circle"
                        className="mb-0"
                    />
                    <Item title="Support" icon="help-circle" className="mb-0" />
                    <div className="border-b border-gray-100" />
                    <Item title="Log out" icon="log-out-01" className="mb-0" />
                </div>
            )}
        </div>
    );
};

export default SideBar;
