import { ComponentPropsWithRef, forwardRef, ForwardedRef } from 'react';
import { Header, Trigger } from '@radix-ui/react-accordion';
import { styled } from '../../stitches.config';

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

const StyledHeader = styled(Header, {
    flexGrow: '1',
});

const StyledTrigger = styled(Trigger, {
    display: 'flex',
    width: '$space$full',
    fontSize: '$sm',
    padding: '$2',
    textAlign: 'left',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderTopWidth: '0',
    borderBottomWidth: '$default',
    borderColor: '$grey-4',
    backgroundColor: '$grey-5',
    cursor: 'pointer',
    color: '$grey-1',
    '&:focus': {
        outline: '2px solid $primary-1',
        outlineOffset: '2px',
    },
    '&:hover': {
        backgroundColor: '$primary-5',
    },
    '&:disabled': {
        backgroundColor: '$base',
        cursor: 'default',
    },
});

const StyledIcon = styled(Icon, {
    width: '$space$6',
    transition: 'transform 300ms cubic-bezier(0.87, 0, 0.13, 1)',
    '[data-state=open] &': { transform: 'rotate(180deg)' },
});

const mdiChevronDown =
    'M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z';

export type AccordionTriggerProps = ComponentPropsWithRef<'h1'>;

/**
 * AccordionTrigger component
 */
const _AccordionTrigger = (
    props: AccordionTriggerProps,
    ref: ForwardedRef<HTMLHeadingElement>,
): JSX.Element => {
    const { children, ...otherProps } = props;
    return (
        <StyledHeader ref={ref} {...otherProps}>
            <StyledTrigger>
                {children}
                <StyledIcon
                    aria-hidden="true"
                    path={mdiChevronDown}
                ></StyledIcon>
            </StyledTrigger>
        </StyledHeader>
    );
};

export const AccordionTrigger = forwardRef(_AccordionTrigger) as (
    props: AccordionTriggerProps & {
        ref?: ForwardedRef<HTMLHeadingElement>;
    },
) => ReturnType<typeof _AccordionTrigger>;
