import { makeStyles } from "@mui/styles"
import Typography from "@mui/material/Typography"
import { FC } from "react"
import { combineClasses } from "../../utils/combineClasses"
import { SectionAction } from "../SectionAction/SectionAction"

type SectionLayout = "fixed" | "fluid"

export interface SectionProps {
  title?: React.ReactNode | string
  description?: React.ReactNode
  toolbar?: React.ReactNode
  alert?: React.ReactNode
  layout?: SectionLayout
  className?: string
  children?: React.ReactNode
}

type SectionFC = FC<React.PropsWithChildren<SectionProps>> & {
  Action: typeof SectionAction
}

export const Section: SectionFC = ({
  title,
  description,
  toolbar,
  alert,
  className = "",
  children,
  layout = "fixed",
}) => {
  const styles = useStyles({ layout })
  return (
    <section className={combineClasses([styles.root, className])}>
      <div className={styles.inner}>
        {(title || description) && (
          <div className={styles.header}>
            <div>
              {title && <Typography variant="h4">{title}</Typography>}
              {description && typeof description === "string" && (
                <Typography className={styles.description}>
                  {description}
                </Typography>
              )}
              {description && typeof description !== "string" && (
                <div className={styles.description}>{description}</div>
              )}
            </div>
            {toolbar && <div>{toolbar}</div>}
          </div>
        )}
        {alert && <div className={styles.alert}>{alert}</div>}
        {children}
      </div>
    </section>
  )
}

// Sub-components
Section.Action = SectionAction

const useStyles = makeStyles((theme) => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    boxShadow: theme.shadows[6],
    marginBottom: theme.spacing(1),
    padding: theme.spacing(6),
    borderRadius: theme.shape.borderRadius,
    border: `1px solid ${theme.palette.divider}`,

    [theme.breakpoints.down("md")]: {
      padding: theme.spacing(4, 3, 4, 3),
    },
  },
  inner: ({ layout }: { layout: SectionLayout }) => ({
    maxWidth: layout === "fluid" ? "100%" : 500,
  }),
  alert: {
    marginBottom: theme.spacing(1),
  },
  header: {
    marginBottom: theme.spacing(4),
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
  },
  description: {
    color: theme.palette.text.secondary,
    fontSize: 16,
    marginTop: theme.spacing(2),
  },
}))
