import Stack from "@mui/material/Stack";
import {isNavItemActive} from "../../lib/isNavItemActive";
import {navIcons} from "../core/navIcons";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import {Link} from "react-router-dom";

export function renderNavItems({items = [], pathname}) {
    const children = items.reduce((acc, curr) => {
        const {key, ...item} = curr;
        acc.push(<NavItem key={key} pathname={pathname} {...item} />);
        return acc;
    }, []);

    return (
        <Stack key={"stack-NavItem-key"} component="ul" spacing={1} sx={{listStyle: 'none', m: 0, p: 0}}>
            {children}
        </Stack>
    );
}

function NavItem({disabled, external, href, icon, matcher, pathname, title}) {
    const active = isNavItemActive({disabled, external, href, matcher, pathname});
    const Icon = icon ? navIcons[icon] : null;

    return (
        <li>
            <Link to={href} style={{ textDecoration: 'none' }}>
                <Box
                    sx={{
                        alignItems: 'center',
                        borderRadius: 1,
                        color: 'var(--NavItem-color)',
                        cursor: 'pointer',
                        display: 'flex',
                        flex: '0 0 auto',
                        gap: 1,
                        p: '6px 16px',
                        position: 'relative',
                        textDecoration: 'none',
                        whiteSpace: 'nowrap',
                        ...(disabled && {
                            bgcolor: 'var(--NavItem-disabled-background)',
                            color: 'var(--NavItem-disabled-color)',
                            cursor: 'not-allowed',
                        }),
                        ...(active && {
                            bgcolor: 'var(--NavItem-active-background)',
                            color: 'var(--NavItem-active-color)'
                        }),
                    }}
                >
                    <Box sx={{alignItems: 'center', display: 'flex', justifyContent: 'center', flex: '0 0 auto'}}>
                        {Icon ? (
                            <Icon
                                fill={active ? 'var(--NavItem-icon-active-color)' : 'var(--NavItem-icon-color)'}
                                fontSize="var(--icon-fontSize-md)"
                                weight={active ? 'fill' : undefined}
                            />
                        ) : null}
                    </Box>
                    <Box sx={{flex: '1 1 auto'}}>
                        <Typography
                            component="span"
                            sx={{color: 'inherit', fontSize: '0.875rem', fontWeight: 500, lineHeight: '28px'}}
                        >
                            {title}
                        </Typography>
                    </Box>
                </Box>
            </Link>
        </li>
    );
}