import React, { useEffect, useState } from "react";
import { Dropdown } from "antd";
import type { MenuProps } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { history } from "@umijs/max";
import logoPng from "@/assets/image/logo.ico";
import logoKailin from "@/assets/image/logo_i.png";
import { products } from "./utils/utils";

const scrollToHash = (hash: string) => {
  if (typeof window === "undefined") return;
  const id = hash.replace(/^#/, "");
  requestAnimationFrame(() => {
    const el = document.getElementById(id);
    el?.scrollIntoView({ behavior: "smooth", block: "start" });
  });
};

const AppRoot: React.FC<React.PropsWithChildren> = (props) => {
  const [pathname, setPathname] = useState(() => history.location.pathname);

  useEffect(() => {
    const toAbsoluteUrl = (url: string) => {
      if (/^https?:\/\//.test(url)) return url;
      const origin = window.location.origin.replace(/\/+$/, "");
      const p = url.startsWith("/") ? url : `/${url}`;
      return `${origin}${p}`;
    };

    const ensureMetaProperty = (property: string) => {
      let meta = document.querySelector(
        `meta[property="${property}"]`,
      ) as HTMLMetaElement | null;
      if (!meta) {
        meta = document.createElement("meta");
        meta.setAttribute("property", property);
        document.head.appendChild(meta);
      }
      return meta;
    };

    ensureMetaProperty("og:type").content = "website";
    ensureMetaProperty("og:url").content = window.location.href;
    ensureMetaProperty("og:image").content = toAbsoluteUrl(logoPng);

    let faviconLink = document.querySelector(
      'link[rel~="icon"]',
    ) as HTMLLinkElement | null;
    if (!faviconLink) {
      faviconLink = document.createElement("link");
      faviconLink.rel = "icon";
      document.head.appendChild(faviconLink);
    }
    faviconLink.type = "image/png";
    faviconLink.href = logoPng;

    let appleTouchIconLink = document.querySelector(
      'link[rel="apple-touch-icon"]',
    ) as HTMLLinkElement | null;
    if (!appleTouchIconLink) {
      appleTouchIconLink = document.createElement("link");
      appleTouchIconLink.rel = "apple-touch-icon";
      document.head.appendChild(appleTouchIconLink);
    }
    appleTouchIconLink.href = logoPng;
  }, []);

  useEffect(() => {
    const unlisten = history.listen(({ location }) => {
      setPathname(location.pathname);
    });
    return unlisten;
  }, []);

  useEffect(() => {
    const { hash } = window.location;
    if (hash && hash.length > 1) {
      scrollToHash(hash);
    }
  }, [pathname]);

  const hideHeader = pathname === "/privacy" || pathname === "/agreement";
  const headerHeight = hideHeader ? 0 : 72;

  const productMenuItems: MenuProps["items"] = products.map((product) => ({
    key: product.name,
    label: (
      <a href={product.url} target="_blank" rel="noreferrer">
        {product.name}
      </a>
    ),
  }));

  const header = hideHeader ? null : (
    <header className="siteHeader">
      <div className="siteHeaderInner">
        <a
          className="siteHeaderBrand"
          onClick={() => history.push("/home")}
        >
          <img className="siteHeaderLogo" src={logoKailin} alt="开邻智数" />
          {/* <span className="siteHeaderWordmark">
            <span className="siteHeaderName">开邻智数</span>
            <span className="siteHeaderEn">Kirin Intelligent Data</span>
          </span> */}
        </a>

        <nav className="siteHeaderNav" aria-label="主导航">
          <button
            type="button"
            className={
              pathname === "/home"
                ? "siteHeaderNavLink siteHeaderNavLinkActive"
                : "siteHeaderNavLink"
            }
            onClick={() => history.push("/home")}
          >
            首页
          </button>

          <Dropdown menu={{ items: productMenuItems }} placement="bottom">
            <button type="button" className="siteHeaderNavLink siteHeaderNavDropdown">
              产品中心
              <DownOutlined className="siteHeaderNavCaret" />
            </button>
          </Dropdown>

          <button
            type="button"
            className={
              pathname === "/solution"
                ? "siteHeaderNavLink siteHeaderNavLinkActive"
                : "siteHeaderNavLink"
            }
            onClick={() => history.push("/solution")}
          >
            联系我们
          </button>

          <button
            type="button"
            className="siteHeaderCta"
            onClick={() => history.push("/solution")}
          >
            获取方案
          </button>
        </nav>
      </div>
    </header>
  );

  return (
    <>
      {header}
      <div style={{ paddingTop: headerHeight }}>{props.children}</div>
    </>
  );
};

export function rootContainer(container: React.ReactNode) {
  return <AppRoot>{container}</AppRoot>;
}
