import { useRef, memo, useMemo } from "react";
import PropTypes from "prop-types";
import { Layout } from "antd";
import ContentRenderer from "../ContentRenderer";
import { useMediaQuery } from "react-responsive";
import { useSettingsContext } from "../../contexts/SettingsContext";
import ShareButton from "../Buttons/ShareButton";

const { Content } = Layout;

const BlogPage = memo(({ blogData }) => {
  const settings = useSettingsContext();
  const isLargeMobile = useMediaQuery({ maxWidth: 1200 });
  const isMobile = useMediaQuery({ maxWidth: 800 });
  const isFullHeight = !useMediaQuery({ maxHeight: 550 });
  const contentRef = useRef(null);

  const theme = useMemo(
    () => settings?.globalThemes?.blog || settings?.themes[0],
    [settings?.globalThemes?.blog, settings?.themes]
  );

  if (blogData == null) {
    return null;
  }

  const blogHeader = (
    <div className="tb-blog-header">
      <div className="tb-blog-header-title">
        <h1
          className={`tb-blog-title ${isMobile ? "tb-blog-title-mobile" : ""}`}
        >
          {blogData?.name || "n/a"}
        </h1>
        <ShareButton blogData={blogData} theme={theme} />
      </div>

      <div className="tb-blog-header-meta">
        <p className="tb-blog-subtitle">{blogData?.subTitle || "n/a"}</p>
        <p className="tb-blog-date">{blogData?.date || "n/a"}</p>
      </div>
    </div>
  );

  return (
    <div
      className={
        !isMobile
          ? "tb-page-container tb-blog-page"
          : "tb-page-container tb-page-container-mobile tb-blog-page"
      }
      style={{
        "--tb-backgroundColor": theme?.backgroundColor,
        "--tb-textColor": theme?.textColor,
        background: "var(--tb-backgroundColor)",
      }}
    >
      <Content
        className={`tb-page-content tb-blog-content ${
          isLargeMobile ? " tb-page-content-mobile tb-blog-content-mobile" : ""
        }`}
        ref={contentRef}
      >
        <div className="tb-content-container-wrapper">
          <div
            className={`tb-content-container tb-content-align-left tb-content-justify-top ${
              isFullHeight ? "tb-content-container-full-height" : ""
            } tb-content-container-vscroll`}
            style={{
              gap: "20px",
            }}
          >
            <ContentRenderer
              content={blogData?.content}
              verticalScroll={true}
              gap={12}
              firstElement={blogHeader}
            />
          </div>
        </div>
      </Content>
    </div>
  );
});

BlogPage.displayName = "BlogPage";

BlogPage.propTypes = {
  blogData: PropTypes.object.isRequired,
};

export default BlogPage;
