import React, { forwardRef } from 'react';

import { theme, styled } from '../../stitches.config';

import { BreadcrumbItem } from './BreadcrumbItem';
import { Icon } from '../Icon';

const StyledBreadcrumbList = styled('ol', {
    display: 'inline-flex',
    alignItems: 'center',
    flexWrap: 'wrap',
    gap: theme.space['1'],
});

const mdiMenuRight = 'M10,17L15,12L10,7V17Z';

export interface BreadcrumbProps extends React.ComponentPropsWithRef<'ol'> {
    /** Seperator to seperate the breadcrumbs */
    seperator?: React.ReactNode;
}

/**
 * Breadcrumb component
 */
export const Breadcrumb = forwardRef<HTMLOListElement, BreadcrumbProps>(
    (props, ref): JSX.Element => {
        const {
            children,
            seperator = <Icon path={mdiMenuRight} />,
            ...otherProps
        } = props;

        // get the count of the valid children
        const count = React.Children.toArray(children).filter(
            (c) => React.isValidElement(c) && c.type === BreadcrumbItem,
        ).length;

        /**
         * Render the children adding in additional properties
         * @returns cloned children elements
         */
        const render = () => {
            let remaining = count;

            return React.Children.map(children, (c, index) => {
                if (React.isValidElement(c) && c.type === BreadcrumbItem) {
                    // remove one
                    remaining--;

                    return (
                        <React.Fragment key={`breadcrumb--${index}`}>
                            {
                                // pass in the hidden props
                                React.cloneElement(c, {
                                    last: remaining === 0,
                                } as React.Attributes)
                            }
                            {remaining !== 0 && seperator}
                        </React.Fragment>
                    );
                }

                return c;
            });
        };

        /* add in if else here for empty href */
        return (
            <StyledBreadcrumbList ref={ref} {...otherProps}>
                {render()}
            </StyledBreadcrumbList>
        );
    },
);

Breadcrumb.displayName = 'Breadcrumb';
