import React, { PropsWithChildren, useState } from "react";

import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
import {
  Box,
  ButtonBase,
  Popover,
  Stack,
  TableCell,
  TableCellProps,
  Typography,
  TypographyProps,
} from "@mui/material";

export interface TableHeadingProps extends PropsWithChildren<TableCellProps> {
  typographyProps?: TypographyProps;
  popover?: React.ReactNode;
  popoverLabel?: React.ReactNode;
}

export const TableHeading: React.FC<TableHeadingProps> = ({
  children,
  typographyProps,
  popover,
  popoverLabel,
  ...props
}) => {
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

  const headingText = (
    <Typography
      {...typographyProps}
      sx={{
        fontWeight: "600",
        fontVariationSettings: { sm: '"wdth" 100', xs: '"wdth" 75' },
        ...typographyProps?.sx,
      }}
      variant="body2"
    >
      {children}
    </Typography>
  );

  return (
    <TableCell {...props}>
      {popover != null ? (
        <>
          <ButtonBase
            sx={{
              position: "relative",
              borderRadius: 1,
              zIndex: 0,
              "&::before": {
                content: '""',
                position: "absolute",
                inset: "-2px -4px",
                borderRadius: 1,
                backgroundColor: "action.hover",
                opacity: 0,
                transition: (theme) =>
                  theme.transitions.create("opacity", {
                    duration: theme.transitions.duration.shortest,
                  }),
                zIndex: -1,
                pointerEvents: "none",
              },
              "&:hover::before, &:focus-visible::before": { opacity: 1 },
              "&:hover .popover-label, &:focus-visible .popover-label": {
                backgroundColor: "transparent",
              },
            }}
            onClick={(e) => setAnchorEl(e.currentTarget)}
          >
            <Stack alignItems="center" direction="row" gap={0.5}>
              {headingText}
              <UnfoldMoreIcon sx={{ color: "text.secondary", width: 16, height: 16 }} />
            </Stack>

            {popoverLabel != null ? (
              <Typography
                className="popover-label"
                color="text.secondary"
                sx={{
                  ml: 0.25,
                  px: 0.5,
                  borderRadius: 1,
                  backgroundColor: "action.hover",
                }}
                variant="body2"
              >
                {popoverLabel}
              </Typography>
            ) : null}
          </ButtonBase>

          <Popover
            anchorEl={anchorEl}
            anchorOrigin={{ horizontal: "center", vertical: "bottom" }}
            open={Boolean(anchorEl)}
            transformOrigin={{ horizontal: "center", vertical: "top" }}
            onClose={() => setAnchorEl(null)}
          >
            <Box p={2}>{popover}</Box>
          </Popover>
        </>
      ) : (
        headingText
      )}
    </TableCell>
  );
};

export default TableHeading;
