'use client';

import * as React from 'react';
import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline';
import { Dialog } from '@headlessui/react';
import clsx from 'clsx';
import NextLink from 'next/link';
import { usePathname } from 'next/navigation';

import { TiDBCloudIcon, GitHubIcon } from '@/components/Icon';
import {
  CLOUD_FREE_TRIAL,
  DOC_CLOUD,
  WEBSITE_DEVELOPER_HUB,
  PRODUCT_TIDB_PRICING,
  PRODUCT_TIDB,
  SITE_HOME,
  SITE_AI,
  GH_PINGCAP_TIDB,
} from '@/constant/url';
import { goToCloudSignupClick, goToGitHubClick } from '@/components/GTM';
import { formatNumber } from '@/utils';

const navigation = [
  { name: 'TiDB Serverless', href: SITE_HOME },
  { name: 'AI', href: SITE_AI },
  { name: 'Documentation', href: DOC_CLOUD },
  { name: 'Developer Hub', href: WEBSITE_DEVELOPER_HUB },
  { name: 'Pricing', href: PRODUCT_TIDB_PRICING },
];

export default function Header(props: {
  className?: string;
  style?: React.CSSProperties;
}) {
  const { className, style } = props;

  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);
  const [stars, setStars] = React.useState<number | null>(null);

  const nextPathname = usePathname();
  // todo: do not use nextPathname.split
  const pageCategoryMemo = React.useMemo(() => {
    const pathList = nextPathname.split('/').filter(Boolean);
    return pathList;
  }, [nextPathname]);

  React.useEffect(() => {
    const getEdgeCfg = async () => {
      const res = await fetch('/api/org/overview');
      const data = await res.json();
      setStars(data?.data?.stars || 0);
    };

    getEdgeCfg();
  }, []);

  return (
    <>
      <header
        className={clsx(
          'sticky top-0 z-[99] bg-darkgrey-950 bg-opacity-50 backdrop-blur-[32px]',
          className,
        )}
        style={style}
      >
        <div className="custom-style-ad-bar h-1 w-full" />
        <nav
          className="mx-auto flex h-[72px] max-w-[1512px] items-center justify-between px-4 sm:px-8 lg:px-12"
          aria-label="Global"
        >
          <div className="flex items-center gap-x-12">
            <NextLink
              href={PRODUCT_TIDB}
              className="-m-1.5 p-1.5"
              target={'_blank'}
            >
              <span className="sr-only">TiDB</span>
              <TiDBCloudIcon className="h-8 w-auto" />
            </NextLink>
            <div className="hidden lg:flex lg:gap-x-12">
              {navigation.map((item) => (
                <NextLink
                  key={item.name}
                  href={item.href}
                  className="text-base leading-6 text-darkgrey-300 hover:text-white"
                  target={item.href.startsWith('/') ? '_self' : '_blank'}
                  style={{
                    color:
                      nextPathname === item.href
                        ? '#fff'
                        : 'rgb(var(--color-dark-grey-7-rgb)',
                  }}
                >
                  {item.name}
                </NextLink>
              ))}
            </div>
          </div>
          {stars && (
            <NextLink
              href={GH_PINGCAP_TIDB}
              target={'_blank'}
              className="ml-auto flex items-center gap-x-1 px-2 text-darkgrey-300 sm:px-4 md:px-8"
              onClick={() => {
                goToGitHubClick({
                  page_category: pageCategoryMemo[0] || '',
                  page_category2: pageCategoryMemo[1] || '',
                  position: 'header',
                });
              }}
            >
              <GitHubIcon className="h-6 w-6 fill-current" />
              <span className="ml-1 text-sm font-semibold">
                {formatNumber(stars)}
              </span>
            </NextLink>
          )}
          <div className="flex lg:hidden">
            <button
              type="button"
              className="text-grey-700 -m-2.5 inline-flex items-center justify-center rounded-md p-2.5"
              onClick={() => setMobileMenuOpen(true)}
            >
              <span className="sr-only">Open main menu</span>
              <Bars3Icon className="h-6 w-6" aria-hidden="true" />
            </button>
          </div>
          <NextLink
            href={CLOUD_FREE_TRIAL}
            className="hidden text-base font-semibold lg:flex"
            target="_blank"
            onClick={goToCloudSignupClick({
              page_category: pageCategoryMemo[0] || '',
              page_category2: pageCategoryMemo[1] || '',
              button_name: 'Start Free',
              position: 'header',
            })}
          >
            <div className="custom-style-button">Start Free</div>
          </NextLink>
        </nav>
        <Dialog
          as="div"
          className="lg:hidden"
          open={mobileMenuOpen}
          onClose={setMobileMenuOpen}
        >
          <div className="fixed inset-0 z-10" />
          <Dialog.Panel className="fixed inset-y-0 right-0 z-[100] w-full overflow-y-auto bg-background px-6 pb-5 pt-6 text-[#fff] sm:max-w-sm sm:ring-1 sm:ring-darkgrey-900/10">
            <div className="flex items-center justify-between">
              <NextLink
                href={PRODUCT_TIDB}
                className="-m-1.5 p-1.5"
                target="_blank"
                onClick={() => setMobileMenuOpen(false)}
              >
                <span className="sr-only">TiDB</span>
                <TiDBCloudIcon className="h-8 w-auto" />
              </NextLink>
              <button
                type="button"
                className="text-grey-700 -m-2.5 rounded-md p-2.5"
                onClick={() => setMobileMenuOpen(false)}
              >
                <span className="sr-only">Close menu</span>
                <XMarkIcon className="h-6 w-6" aria-hidden="true" />
              </button>
            </div>
            <div className="mt-6 flow-root">
              <div className="-my-6 divide-y divide-darkgrey-500/10">
                <div className="space-y-2 py-6">
                  {navigation.map((item) => (
                    <NextLink
                      key={item.name}
                      href={item.href}
                      className="hover:bg-darkgrey-50 -mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-darkgrey-300 hover:text-white"
                      target={item.href.startsWith('/') ? '_self' : '_blank'}
                      style={{
                        color:
                          nextPathname === item.href
                            ? '#fff'
                            : 'rgb(var(--color-dark-grey-7-rgb)',
                      }}
                      onClick={() => setMobileMenuOpen(false)}
                    >
                      {item.name}
                    </NextLink>
                  ))}
                </div>
                <div className="py-6">
                  <NextLink
                    href={CLOUD_FREE_TRIAL}
                    className="hover:bg-darkgrey-50 -mx-3 block rounded-lg px-3 py-2.5 text-base font-semibold leading-7 text-darkgrey-300 hover:text-white"
                    target="_blank"
                    onClick={goToCloudSignupClick({
                      page_category: pageCategoryMemo[0] || '',
                      page_category2: pageCategoryMemo[1] || '',
                      button_name: 'Start Free',
                      position: 'header',
                    })}
                  >
                    Start Free
                  </NextLink>
                </div>
              </div>
            </div>
          </Dialog.Panel>
        </Dialog>
      </header>
    </>
  );
}
