import React, { FC, useState } from 'react';
import { Box, BoxProps } from '../Box';
import { Flex } from '../Flex';
import { Heading } from '../Heading';
import { IconCircled } from '../IconCircled';
import { SvgChevron } from '../../assets/images/icons';

const variants = {
  light: { bg: 'white', borderRadius: '3', boxShadow: '5', p: '4', mb: '1' },
  transparent: {},
} as const;

export type Props = {
  title: string;
  defaultOpen?: boolean;
  clickable?: boolean;
  variant?: keyof typeof variants;
  onClick?: (state: boolean) => void;
} & BoxProps;

export const CollapsableCard: FC<Props> = (props) => {
  const {
    title,
    defaultOpen,
    clickable = true,
    onClick,
    children,
    variant = 'light',
    ...restProps
  } = props;
  const [isOpen, setIsOpen] = useState(!!defaultOpen);

  const toggle = () => {
    const newState = !isOpen;
    setIsOpen(newState);
    if (onClick) onClick(newState);
  };

  const clickableProps = {
    onClick: toggle,
    style: { cursor: 'pointer' },
  };

  return (
    <Box {...variants[variant]} {...restProps}>
      <Flex
        justifyContent="space-between"
        {...(clickable ? clickableProps : {})}
      >
        <Box mr="24px">
          <Heading variant="h5">{title}</Heading>
        </Box>
        <Box>
          <IconCircled
            Asset={SvgChevron}
            scale={0.75}
            width={32}
            height={32}
            color={isOpen ? 'brandMain' : 'gray.3'}
            bg={isOpen ? 'brandLightest' : 'gray.4'}
            rotate={isOpen ? undefined : '180deg'}
            {...(clickable ? {} : clickableProps)}
          />
        </Box>
      </Flex>
      {isOpen && <Box mt="4">{children}</Box>}
    </Box>
  );
};
