import React from 'react';
import { Button, UserThumb } from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import { MainNavLink } from './mainNavLink';
import type { MainNavLinkOptions } from '../../types';
import type { BaseUser } from '@theorchard/suite-identity';

export interface MainNavFooterUserMenuProps<AppData = unknown> {
    items?: MainNavLinkOptions<AppData>[];
    onClick?: () => void;
    name?: string;
    picture?: string;
    testId?: string;
    className?: string;
    impersonatedBy?: BaseUser;
}

const CLASS_NAME = 'MainNavFooterUserMenu';
const CLASS_NAME_NAME = `${CLASS_NAME}-name`;
const CLASS_NAME_PICTURE = `${CLASS_NAME}-picture`;
const CLASS_NAME_TOGGLE = `${CLASS_NAME}-toggle`;
const CLASS_NAME_TOGGLE_MENU = 'MainNavFooterToggleMenu';

export function MainNavFooterUserMenu<AppData>({
    items = [],
    onClick,
    name,
    picture,
    className,
    testId = CLASS_NAME,
}: MainNavFooterUserMenuProps<AppData>) {
    return (
        <>
            <div
                role="button"
                tabIndex={0}
                className={cx(CLASS_NAME, className)}
                data-testid={testId}
                onClick={onClick}
                onKeyDown={(e) => e.key === 'enter' && onClick?.()}
            >
                <span className={CLASS_NAME_PICTURE}>
                    <UserThumb image={picture} name={name} />
                </span>
                <span className={CLASS_NAME_NAME}>{name}</span>

                <Button
                    className={CLASS_NAME_TOGGLE}
                    variant="link"
                    size="sm"
                    aria-label="Show menu"
                >
                    <GlyphIcon name="optionsHorizontal" size={16} />
                </Button>
            </div>
            <nav onClickCapture={onClick} className={CLASS_NAME_TOGGLE_MENU}>
                {items.map((item, index) => {
                    if (!item.path)
                        throw new Error(
                            `The mainNav.footer has an item [${index}] without a valid "path".`
                        );

                    if (item.Component) return <item.Component key={item.path} {...item} />;
                    return <MainNavLink key={item.path} {...item} />;
                })}
            </nav>
        </>
    );
}
