import { useState } from 'react';
import Button from '../../atoms/Button/Button';
import Text from '../../atoms/Text/Text';
import { ButtonProps } from '../../atoms/Button/Button';
import { ChevronDown, ChevronUp } from '@carbon/icons-react';

export interface CollapseProps extends ButtonProps {
    /**
     * Text for the main button .
     */
    text: string;
    /**
     * If the collapse is expanded .
     */
    isExpanded?: boolean;
}

const Collapse: React.FC<CollapseProps> = (props) => {
    const { className, children, text, isExpanded } = props;
    const [expanded, setExpanded] = useState(isExpanded);

    const elementProps = Object.assign({}, props);
    delete elementProps.isExpanded;
    delete elementProps.children;

    return (
        <>
            <Button
                {...elementProps}
                onClick={() => {
                    setExpanded(!expanded);
                }}
                className={`justify-start text-left w-full pr-2 ${className} `}
            >
                <Text className="flex-auto pr-3">{text}</Text>
                {expanded ? (
                    <ChevronUp size={24} className="mr-1 shrink-0" />
                ) : (
                    <ChevronDown size={24} className="mr-1 shrink-0" />
                )}
            </Button>
            {<div className={`flex-col w-full ${expanded ? 'flex' : 'hidden'} `}>{children}</div>}
        </>
    );
};

Collapse.defaultProps = {
    isExpanded: false,
};

export default Collapse;
