import { useState } from 'react';

import ExpandLess from '@material-hu/icons/material/ExpandLess';
import ExpandMore from '@material-hu/icons/material/ExpandMore';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Collapse from '@material-hu/mui/Collapse';
import Stack from '@material-hu/mui/Stack';
import Typography, { type TypographyProps } from '@material-hu/mui/Typography';
import * as animations from '@material-hu/utils/animations';

type CollapsibleSectionProps = {
  defaultOpen?: boolean;
  title: string;
  children: React.ReactNode;
  titleProps?: TypographyProps;
};

const CollapsibleSection = ({
  title,
  children,
  defaultOpen = false,
  titleProps,
}: CollapsibleSectionProps) => {
  const [open, setOpen] = useState(defaultOpen);
  const iconStyle = { animation: `${animations.fadeIn} 200ms ease-in-out` };

  const handleToggle = () => setOpen(!open);

  return (
    <Stack
      sx={{
        backgroundColor: theme => theme.palette.new.background.layout.default,
        borderRadius: 1,
      }}
    >
      <ButtonBase
        onClick={handleToggle}
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 2,
          justifyContent: 'space-between',
          textAlign: 'start',
          cursor: 'default',
          padding: 2,
        }}
        disableRipple
      >
        <Typography
          {...titleProps}
          sx={{ flex: 1, ...titleProps?.sx }}
        >
          {title}
        </Typography>
        {open && <ExpandLess sx={iconStyle} />}
        {!open && <ExpandMore sx={iconStyle} />}
      </ButtonBase>
      <Collapse
        in={open}
        sx={{ padding: 2, paddingBottom: open ? 2 : 0, pt: 0 }}
        timeout="auto"
      >
        {children}
      </Collapse>
    </Stack>
  );
};

export default CollapsibleSection;
