import React, { memo, useState } from 'react';
import { useSpring, animated } from 'react-spring';
import { Title, DownIcon, Content, Frame, Row, IconContainer } from './style';
import { useMeasure, usePrevious } from 'utils/hooks';
export type IProps = {
    /** 项目的标题 */
    label: string;
    /** 是否默认开启 */
    defaultOpen?: boolean;
    /** 是否选中 */
    selected?: boolean;
    /** TreeItem的值 */
    value?: string | number | boolean;
    /** 选中回调函数 */
    onChange?: (value?: string | number | boolean) => void;
    children?: React.ReactNode;
    style?: React.CSSProperties;
    className?: string;
};
export const Tree = ({ children, label, style, selected, value, onChange, defaultOpen = false }: IProps) => {
    const [isOpen, setOpen] = useState(defaultOpen);
    const previous = usePrevious(isOpen);
    const [bind, { height: viewHeight }] = useMeasure();
    const { height, opacity, transform } = useSpring<any>({
        from: { height: 0, opacity: 0, transform: 'translate3d(20px,0,0)' },
        to: {
            height: isOpen ? viewHeight : 0,
            opacity: isOpen ? 1 : 0,
            transform: `translate3d(${isOpen ? 0 : 20}px,0,0)`,
        },
    });
    return (
        <Frame>
            <Row>
                {children && (
                    <IconContainer onClick={() => setOpen(!isOpen)}>
                        <DownIcon isOpen={isOpen} />
                    </IconContainer>
                )}
                <Title
                    style={style}
                    selected={selected}
                    onClick={() => {
                        onChange && onChange(value);
                    }}
                >
                    {label}
                </Title>
            </Row>
            <Content style={{ opacity, height: isOpen && previous === isOpen ? 'auto' : height }}>
                <animated.div
                    style={{ transform, display: 'inline-flex', flexDirection: 'column' }}
                    {...bind}
                    children={children}
                />
            </Content>
        </Frame>
    );
};

export default memo(Tree);
