import { ReactNode, useState } from 'react';

import { Box, Button, Typography } from '@mui/material';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { makeStyles } from 'tss-react/mui';

interface Props {
  action?: ReactNode;
  children: ReactNode;
  defaultOpen?: boolean;
  title: string;
}

const useStyles = makeStyles()(theme => ({
  section: { marginTop: 40 },
  // Header border runs edge-to-edge to the sidebar; text is inset to align with
  // the module title. Chevron sits in the left gutter.
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    borderBottom: `1px solid ${theme.palette.divider}`,
    paddingBottom: 12,
    paddingLeft: 50
  },
  // Chevron sits in the left gutter, absolutely positioned like the legacy
  // `.section > a::before`, so it stays inline with the title regardless of flow.
  titleRow: {
    position: 'relative',
    padding: 0,
    minWidth: 0,
    color: theme.palette.text.primary,
    '&:hover': { backgroundColor: 'transparent' }
  },
  chevron: { position: 'absolute', left: -34, top: 0, color: theme.palette.text.primary },
  body: { marginTop: 12, paddingLeft: 50 }
}));

export const CollapsibleSection = ({ action, children, defaultOpen = true, title }: Props) => {
  const { classes } = useStyles();
  const [open, setOpen] = useState(defaultOpen);

  return (
    <Box className={classes.section}>
      <Box className={classes.header}>
        <Button
          className={classes.titleRow}
          color="inherit"
          disableRipple
          onClick={() => setOpen(o => !o)}
          aria-expanded={open}
        >
          {open ? <ExpandMoreIcon className={classes.chevron} /> : <ExpandLessIcon className={classes.chevron} />}
          <Typography component="span" variant="h3">
            {title}
          </Typography>
        </Button>
        {action}
      </Box>
      {open && <Box className={classes.body}>{children}</Box>}
    </Box>
  );
};
