'use client';

import * as React from 'react';
import {
  StarIcon,
  EyeIcon,
  BookOpenIcon,
  FlagIcon,
  CodeBracketIcon,
  AcademicCapIcon,
  CheckBadgeIcon,
  BriefcaseIcon,
  AtSymbolIcon,
  ChevronDownIcon,
} from '@heroicons/react/24/outline';
import { Dialog, DialogPanel } from '@headlessui/react';
import clsx from 'clsx';
import NextLink from 'next/link';
import NextImage from 'next/image';
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';

import {
  UserIcon,
  MenuTiIcon,
  MenuGraphIcon,
  MenuFaderIcon,
  MenuChartIcon,
  MenuChartLineIcon,
  MenuBankIcon,
  MenuInfinityIcon,
  MenuProjectorIcon,
  MenuNewspaperIcon,
  MenuFilmIcon,
  MenuUsersThreeIcon,
  MenuBuildingIcon,
  MenuHandshakeIcon,
  MenuFileCloudIcon,
  MenuFileIcon,
  MenuFileSearchIcon,
  MenuVectorIcon,
} from '@/components/Icon';
import {
  WEBSITE_DEMO,
  WEBSITE_START,
  WEBSITE_AI,
  PRODUCT,
  ECOSYSTEM,
  SOLUTION,
  RESOURCE,
  DOC_GUID,
  DOC_TIDB,
  DOC_CLOUD,
  SITE_JP,
  COMPANY,
  COMPANY_LEGAL_DOCUMENTS,
  COMPANY_RELEASE_SUPPORT,
  TiDB_CLOUD_SIGN_IN,
  CLOUD_FREE_TRIAL,
} from '@/constant/url';
import { GTMEvent } from '@/components/GTM';

import styles from './header.module.css';

const navigation = [
  {
    name: 'Product',
    menu: [
      {
        type: 'feature',
        submenu: [
          {
            icon: <MenuTiIcon />,
            text: 'TiDB',
            href: PRODUCT.TIDB,
            desc: 'The most advanced, open source, distributed SQL database',
          },
          {
            icon: <MenuTiIcon />,
            text: 'TiDB Dedicated',
            href: PRODUCT.TIDB_DEDICATED,
            desc: 'A fully-managed cloud DBaaS for predictable workloads',
          },
          {
            icon: <MenuTiIcon />,
            text: 'TiDB Serverless',
            href: PRODUCT.TIDB_SERVERLESS,
            desc: 'A fully-managed cloud DBaaS for auto-scaling workloads',
          },
          {
            text: 'Pricing',
            href: PRODUCT.PRICING,
          },
        ],
      },
      {
        type: 'column',
        title: 'Ecosystem',
        submenu: [
          {
            icon: <MenuGraphIcon />,
            text: 'Integrations',
            href: ECOSYSTEM.INTEGRATIONS,
          },
          {
            icon: <MenuFaderIcon />,
            text: 'TiKV',
            href: ECOSYSTEM.TIKV,
          },
          {
            icon: <StarIcon />,
            text: 'TiSpark',
            href: ECOSYSTEM.TISPARK,
          },
          {
            icon: <EyeIcon />,
            text: 'OSS Insight',
            href: ECOSYSTEM.OSS_INSIGHT,
          },
        ],
      },
    ],
  },
  {
    name: 'Solutions',
    menu: [
      {
        type: 'column',
        title: 'By Use Case',
        submenu: [
          {
            icon: <MenuChartIcon />,
            text: 'Accelerate Business Growth',
            href: SOLUTION.ACCELERATE,
          },
          {
            icon: <MenuChartLineIcon />,
            text: 'Handle Unpredictable Traffic Surges',
            href: SOLUTION.TRAFFIC,
          },
          {
            icon: <MenuBankIcon />,
            text: 'Process Payments Reliably',
            href: SOLUTION.PAYMENT,
          },
          {
            icon: <MenuInfinityIcon />,
            text: 'Web3 Insights and Infrastructure',
            href: SOLUTION.WEB3,
          },
          {
            icon: <MenuProjectorIcon />,
            text: 'Extract Operational Insights',
            href: SOLUTION.OPERATIONAL,
          },
        ],
      },
      {
        type: 'feature',
        submenu: [
          {
            text: 'Customer Stories',
            href: SOLUTION.CASE_STUDY,
            desc: 'Trusted and Verified by Innovation Leaders around the world',
          },
        ],
      },
    ],
  },
  {
    name: 'Resources',
    menu: [
      {
        title: 'Learn',
        type: 'column',
        submenu: [
          {
            icon: <MenuNewspaperIcon />,
            text: 'Blog',
            href: RESOURCE.BLOG,
          },
          {
            icon: <BookOpenIcon />,
            text: 'eBooks & Whitepapers',
            href: RESOURCE.EBOOK,
          },
          {
            icon: <MenuFilmIcon />,
            text: 'Videos & Replays',
            href: RESOURCE.VIDEO,
          },
        ],
      },
      {
        title: 'Engage',
        type: 'column',
        submenu: [
          {
            icon: <FlagIcon />,
            text: 'Events & Webinars',
            href: RESOURCE.EVENT,
          },
          {
            icon: <CodeBracketIcon />,
            text: 'Developer Hub',
            href: RESOURCE.DEVELOPER,
          },
          {
            icon: <MenuUsersThreeIcon />,
            text: 'Community Forum',
            href: RESOURCE.FORUM,
          },
        ],
      },
      {
        title: 'PingCAP University',
        type: 'column',
        submenu: [
          {
            icon: <AcademicCapIcon />,
            text: 'Education',
            href: RESOURCE.EDUCATION,
          },
          {
            icon: <CheckBadgeIcon />,
            text: 'Certification',
            href: RESOURCE.CERTIFICATION,
          },
        ],
      },
    ],
  },
  {
    name: 'Company',
    menu: [
      {
        title: 'About',
        type: 'column',
        submenu: [
          {
            icon: <MenuNewspaperIcon />,
            text: 'Press Releases & News',
            href: COMPANY.NEWS,
          },
          {
            icon: <MenuBuildingIcon />,
            text: 'About Us',
            href: COMPANY.ABOUT_US,
          },
          {
            icon: <BriefcaseIcon />,
            text: 'Careers',
            href: COMPANY.CAREERS,
          },
          {
            icon: <MenuHandshakeIcon />,
            text: 'Partners',
            href: COMPANY.PARTNERS,
          },
          {
            icon: <AtSymbolIcon />,
            text: 'Contact Us',
            href: COMPANY.CONTACT_US,
          },
        ],
      },
      {
        type: 'feature',
        submenu: [
          {
            text: 'Legal',
            href: COMPANY.LEGAL,
            desc: 'We will provide you with information related to the contract',
          },
          {
            text: 'Trust Center',
            href: COMPANY.TRUST_CENTER,
            desc: 'How PingCAP ensures the confidentiality and availability of your data',
          },
        ],
      },
    ],
  },
  {
    name: 'Docs',
    menu: [
      {
        type: 'column',
        title: 'Documentation',
        submenu: [
          {
            icon: <MenuFileCloudIcon />,
            text: 'TiDB Cloud Docs',
            href: DOC_CLOUD,
          },
          {
            icon: <MenuFileIcon />,
            text: 'TiDB Docs',
            href: DOC_TIDB,
          },
          {
            icon: <MenuFileSearchIcon />,
            text: 'Developer Guide',
            href: DOC_GUID,
          },
        ],
      },
    ],
  },
];

const mobile_navigation = [
  {
    name: 'Product',
    menu: [
      { text: 'TiDB', href: PRODUCT.TIDB },
      { text: 'TiDB Dedicated', href: PRODUCT.TIDB_DEDICATED },
      { text: 'TiDB Serverless', href: PRODUCT.TIDB_SERVERLESS },
      { text: 'Pricing', href: PRODUCT.PRICING },
      {
        title: 'Capabilities',
        submenu: [{ text: 'Vector Search', href: WEBSITE_AI }],
      },
      {
        title: 'Ecosystem',
        submenu: [
          { text: 'Integrations', href: ECOSYSTEM.INTEGRATIONS },
          { text: 'TiKV', href: ECOSYSTEM.TIKV },
          { text: 'TiSpark', href: ECOSYSTEM.TISPARK },
          { text: 'OSS Insight', href: ECOSYSTEM.OSS_INSIGHT },
        ],
      },
    ],
  },
  {
    name: 'Solutions',
    menu: [
      { text: 'Customer Stories', href: SOLUTION.CUSTOMER },
      {
        title: 'By Use Case',
        submenu: [
          { text: 'Accelerate Business Growth', href: SOLUTION.ACCELERATE },
          {
            text: 'Handle Unpredictable Traffic Surges',
            href: SOLUTION.TRAFFIC,
          },
          { text: 'Process Payments Reliably', href: SOLUTION.PAYMENT },
          { text: 'Web3 Insights and Infrastructure', href: SOLUTION.WEB3 },
          { text: 'Extract Operational Insights', href: SOLUTION.OPERATIONAL },
        ],
      },
    ],
  },
  {
    name: 'Resources',
    menu: [
      {
        title: 'Learn',
        submenu: [
          { text: 'Blog', href: RESOURCE.BLOG },
          { text: 'eBooks & Whitepapers', href: RESOURCE.EBOOK },
          { text: 'Videos & Replays', href: RESOURCE.VIDEO },
        ],
      },
      {
        title: 'Engage',
        submenu: [
          { text: 'Events & Webinars', href: RESOURCE.EVENT },
          { text: 'Developer Hub', href: RESOURCE.DEVELOPER },
          { text: 'Community Forum', href: RESOURCE.FORUM },
          { text: 'HTAP Summit', href: RESOURCE.HTAP_SUMMIT },
        ],
      },
      {
        title: 'PingCAP University',
        submenu: [
          { text: 'Education', href: RESOURCE.COURSES },
          { text: 'Certifications', href: RESOURCE.CERTIFICATION },
        ],
      },
    ],
  },
  {
    name: 'Company',
    menu: [
      { text: 'Legal', href: COMPANY.LEGAL },
      { text: 'Trust Center', href: COMPANY.TRUST_CENTER },
      {
        title: 'About',
        submenu: [
          { text: 'Press Releases & News', href: COMPANY.NEWS },
          { text: 'About Us', href: COMPANY.ABOUT_US },
          { text: 'Careers', href: COMPANY.CAREERS },
          { text: 'Partners', href: COMPANY.PARTNERS },
          { text: 'News', href: COMPANY.NEWS },
          { text: 'Contact Us', href: COMPANY.CONTACT_US },
        ],
      },
    ],
  },
  {
    name: 'Docs',
    menu: [
      {
        title: 'Documentation',
        submenu: [
          { text: 'TiDB Cloud Docs', href: DOC_CLOUD },
          { text: 'TiDB Docs', href: DOC_TIDB },
          { text: 'Developer Guide', href: DOC_GUID },
        ],
      },
    ],
  },
];

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

  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);

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

  const t = useTranslations('Menu');

  return (
    <>
      <header
        className={clsx(
          'sticky top-0 z-[99] bg-[#20222b] backdrop-blur-[32px]',
          className,
        )}
        style={style}
      >
        <div className="custom-style-bg-bar py-2">
          <div className="mx-auto flex max-w-[1512px] justify-end px-4 sm:px-8 lg:px-12">
            <NextLink
              href={TiDB_CLOUD_SIGN_IN}
              className="flex items-center justify-end gap-1 text-sm font-bold text-white"
              target={'_blank'}
            >
              <UserIcon className="opacity-65 h-[18px] w-auto text-white" />
              <span className="pr-1.5 font-bold">Sign In</span>
            </NextLink>
          </div>
        </div>
        <nav
          className="mx-auto flex max-w-[1512px] items-center justify-between px-4 py-3 sm:px-8 lg:px-12"
          aria-label="Global"
        >
          <NextLink
            href={SITE_JP}
            className="flex items-center"
            target={'_blank'}
          >
            <span className="sr-only">PingCAP</span>
            <NextImage
              src="/PingCAP-logo.png"
              alt="pingcap"
              width={132}
              height={32}
              className="h-[34px] w-[132px] md:h-[40px] md:w-[150px]"
            />
          </NextLink>

          <div className="hidden items-center lg:flex lg:gap-x-8">
            {navigation.map((menus) => (
              <div className={styles.menu} key={menus.name}>
                <div className={styles.menuTitle}>{t(menus.name)}</div>
                <div className={styles.menuDropdown}>
                  <div className={styles.menuDropdownInner}>
                    {menus.menu.map((menu) => (
                      <>
                        {menu.type === 'feature' && (
                          <FeatureMenu menu={menu.submenu} />
                        )}
                        {menu.type === 'column' && (
                          <div className={styles.menuColumn}>
                            {menu.title === 'Ecosystem' && (
                              <div className="mb-6 flex flex-col gap-4">
                                <div className="text-base text-white">
                                  Capabilities
                                </div>
                                <ColumnMenu
                                  menu={[
                                    {
                                      text: 'Vector Search',
                                      href: WEBSITE_AI,
                                      icon: <MenuVectorIcon />,
                                    },
                                  ]}
                                />
                              </div>
                            )}
                            <div className="text-base text-white">
                              {t(menu.title)}
                            </div>
                            <ColumnMenu menu={menu.submenu} />
                          </div>
                        )}
                      </>
                    ))}
                  </div>
                </div>
              </div>
            ))}

            <div className="flex gap-2.5">
              <NextLink
                href={COMPANY.CONTACT_US.replace(
                  'www.pingcap.com',
                  'pingcap.co.jp',
                )}
                className="hidden text-base font-bold lg:flex"
                target="_blank"
                onClick={GTMEvent({
                  event: 'go_to_lead_form_page',
                  page_category: pageCategoryMemo[0] || '',
                  page_category2: pageCategoryMemo[1] || '',
                  button_name: 'Contact us',
                  position: 'header',
                })}
              >
                <div className="custom-style-outline-button menu-cta">
                  {t('Contact Us')}
                </div>
              </NextLink>
              <NextLink
                href={CLOUD_FREE_TRIAL}
                className="hidden text-base font-bold lg:flex"
                target="_blank"
                onClick={GTMEvent({
                  event: 'event:event:go_to_cloud_signup',
                  page_category: pageCategoryMemo[0] || '',
                  page_category2: pageCategoryMemo[1] || '',
                  button_name: 'Start Free',
                  position: 'header',
                  product_type: 'serverless',
                })}
              >
                <div className="custom-style-button menu-cta">
                  {t('Start Free')}
                </div>
              </NextLink>
            </div>
          </div>

          <div className="flex lg:hidden">
            <button
              type="button"
              className={styles.mobileMenuButton}
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            >
              <span className={styles.mobileMenuButtonBox}>
                <span
                  className={clsx(styles.mobileMenuButtonInner, {
                    [styles.active]: mobileMenuOpen,
                  })}
                ></span>
              </span>
            </button>
          </div>
        </nav>
        <Dialog
          as="div"
          className="lg:hidden"
          open={mobileMenuOpen}
          onClose={() => setMobileMenuOpen(false)}
        >
          <div className="fixed inset-0 z-10" />
          <DialogPanel className="fixed bottom-0 left-0 right-0 top-[94px] z-[100] w-full overflow-y-auto bg-[#20222b] px-6 pb-5 pt-6 text-[#fff] md:top-[100px]">
            {mobile_navigation.map((item) => (
              <div className={styles.mobileMenu} key={item.name}>
                <input className="hidden" type="checkbox" id={item.name} />
                <label
                  className="flex items-center justify-between border-t border-white/30  py-4"
                  htmlFor={item.name}
                >
                  <div className="text-lg font-bold uppercase text-white">
                    {t(item.name)}
                  </div>
                  <ChevronDownIcon className="h-4 -rotate-90" />
                </label>
                <div className={styles.mobileMenuGroup}>
                  {item.menu.map((menu) => (
                    <MobileMenuItem menu={menu} key={menu.text} />
                  ))}
                </div>
              </div>
            ))}
            <div className="flex gap-4 border-t border-white/30 pb-10 pt-8">
              <NextLink
                href={COMPANY.CONTACT_US.replace(
                  'www.pingcap.com',
                  'pingcap.co.jp',
                )}
                className="text-base font-bold"
                target="_blank"
                onClick={GTMEvent({
                  event: 'go_to_lead_form_page',
                  page_category: pageCategoryMemo[0] || '',
                  page_category2: pageCategoryMemo[1] || '',
                  button_name: 'Contact us',
                  position: 'header',
                })}
              >
                <div className="custom-style-outline-button menu-cta">
                  {t('Contact Us')}
                </div>
              </NextLink>
              <NextLink
                href={CLOUD_FREE_TRIAL}
                className="text-base font-bold"
                target="_blank"
                onClick={GTMEvent({
                  event: 'event:event:go_to_cloud_signup',
                  page_category: pageCategoryMemo[0] || '',
                  page_category2: pageCategoryMemo[1] || '',
                  button_name: 'Start Free',
                  position: 'header',
                  product_type: 'serverless',
                })}
              >
                <div className="custom-style-button menu-cta">
                  {t('Start Free')}
                </div>
              </NextLink>
            </div>
          </DialogPanel>
        </Dialog>
      </header>
    </>
  );
}

const FeatureMenu = (props: any) => {
  const { menu } = props;
  const t = useTranslations('Menu');

  return (
    <div className={styles.menuFeature}>
      {menu.map((item: any) => (
        <div className={styles.menuFeatureItem} key={item.text}>
          <div className="flex items-center gap-2.5">
            {item.icon}
            <NextLink
              href={item.href.replace('www.pingcap.com', 'pingcap.co.jp')}
              className="custom-style-button-link"
              onClick={GTMEvent({
                event: 'jp_navi_click',
                item_name: `${item.text}`,
              })}
            >
              {t(item.text)}
            </NextLink>
          </div>
          {item.desc && (
            <p className="mt-3 text-sm text-[#a9aaaf]">{t(item.desc)}</p>
          )}
        </div>
      ))}
    </div>
  );
};

const ColumnMenu = (props: any) => {
  const { menu } = props;
  const t = useTranslations('Menu');

  return menu.map((item: any) => (
    <NextLink
      key={item.text}
      href={item.href.replace('www.pingcap.com', 'pingcap.co.jp')}
      className="flex min-w-[200px] gap-2.5 text-sm text-[#a9aaaf] hover:text-white hover:opacity-40"
      onClick={GTMEvent({
        event: 'jp_navi_click',
        item_name: `${item.text}`,
      })}
      target={item.href.includes('www.pingcap.com') ? '_self' : '_blank'}
    >
      {item.icon}
      {item.text && t(item.text)}
    </NextLink>
  ));
};

const MobileMenuItem = (props: {
  menu: {
    title?: string;
    text?: string;
    href?: string;
    submenu?: {
      text: string;
      href: string;
    }[];
  };
}) => {
  const { menu } = props;
  const t = useTranslations('Menu');

  if (menu.title) {
    return (
      <div>
        <div className="mt-4 pb-4 text-sm font-bold text-white opacity-30">
          {t(menu.title)}
        </div>
        <div className="flex flex-col gap-4">
          {menu.submenu &&
            menu.submenu.map((item) => (
              <NextLink
                key={item.text}
                href={item.href.replace('www.pingcap.com', 'pingcap.co.jp')}
                className="text-sm text-white hover:text-white hover:opacity-40"
                onClick={GTMEvent({
                  event: 'jp_navi_click',
                  item_name: `${item.text}`,
                })}
              >
                {t(item.text)}
              </NextLink>
            ))}
        </div>
      </div>
    );
  } else {
    return (
      <NextLink
        href={menu.href || ''}
        className="font-bold"
        onClick={GTMEvent({
          event: 'jp_navi_click',
          item_name: `${menu.text}`,
        })}
      >
        {t(menu.text)}
      </NextLink>
    );
  }
};
