import * as React from "react";
import NextLink from "next/link";
import Typography from "@mui/material/Typography";

const CustomHeading = (props: {
  component: "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
  id?: string;
  children?: React.ReactNode;
}) => {
  const { id, children } = props;
  const [showAnchor, setShowAnchor] = React.useState(false);

  const timerRef = React.useRef<NodeJS.Timeout | null>(null);

  const handleMouseEnter = () => {
    setShowAnchor(true);
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
  };
  const handleMouseLeave = () => {
    if (showAnchor) {
      timerRef.current = setTimeout(() => setShowAnchor(false), 300);
    }
  };

  if (id) {
    return (
      <>
        <Typography
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
          sx={{
            color: "text.primary",
            scrollMarginTop: "64px",
            position: "relative",

            // "&:hover": {
            //   textDecoration: "none",

            //   "&:before": {
            //     content: '"#"',
            //     position: "relative",
            //     marginLeft: "-1.2ch",
            //     paddingRight: "0.2ch",
            //   },
            // },
          }}
          {...props}
        >
          {children}
          <Typography
            hidden={!showAnchor}
            component={NextLink}
            href={`#${id}`}
            className="headings"
            sx={{
              color: "text.primary",
              fontSize: "inherit",
              fontWeight: "inherit",
              lineHeight: "inherit",
              position: "absolute",
              top: "0",
              left: "-1.2ch",
            }}
          >
            #
          </Typography>
        </Typography>
      </>
    );
  }
  return <Typography {...props} />;
};

const H1 = (props: any) => <CustomHeading component="h1" {...props} />;
const H2 = (props: any) => <CustomHeading component="h2" {...props} />;
const H3 = (props: any) => <CustomHeading component="h3" {...props} />;
const H4 = (props: any) => <CustomHeading component="h4" {...props} />;
const H5 = (props: any) => <CustomHeading component="h5" {...props} />;
const H6 = (props: any) => <CustomHeading component="h6" {...props} />;

export const Headings = {
  h1: H1,
  h2: H2,
  h3: H3,
  h4: H4,
  h5: H5,
  h6: H6,
};
