'use client';

import * as React from 'react';
import NextLink from 'next/link';
import { usePathname } from 'next/navigation';

import { PRODUCT, RESOURCE, COMPANY, SOCIAL, PRIVACY } from '@/constant/url';
import { SocialIcon, Spinner, TiDBCloudIcon } from '@/components/Icon';
import { submitHSForm } from '@/lib/hsForm';
import { leadFormSubmitClick, leadFormSubmitComplete } from '@/components/GTM';
import { getQueryParams } from '@/utils';

export const navigation = {
  product: [
    { name: 'TiDB', href: PRODUCT.TIDB },
    { name: 'TiDB Dedicated', href: PRODUCT.TIDB_DEDICATED },
    { name: 'TiDB Serverless', href: PRODUCT.TIDB_SERVERLESS },
    { name: 'Pricing', href: PRODUCT.TIDB_PRICING },
    { name: 'Book a demo', href: PRODUCT.TIDB_DEMO },
    { name: 'Start Instantly', href: PRODUCT.TIDB_GET_STARTED },
  ],
  resource: [
    { name: 'Blog', href: RESOURCE.BLOG },
    { name: 'Forum', href: RESOURCE.FORUM },
    { name: 'Event & Webinars', href: RESOURCE.EVENT },
    { name: 'Docs', href: RESOURCE.DOCS },
    { name: 'Developer Guide', href: RESOURCE.DEV_GUIDE },
    { name: 'FAQs', href: RESOURCE.FAQ },
  ],
  company: [
    { name: 'About us', href: COMPANY.ABOUT_US },
    { name: 'News', href: COMPANY.NEWS },
    { name: 'Contact us', href: COMPANY.CONTACT_US },
    { name: 'Trust Center', href: COMPANY.COMPLIANCE },
    { name: 'Security', href: COMPANY.SECURITY },
  ],
  legal: {
    privacy: { name: 'Privacy', href: PRIVACY },
  },
  social: [
    {
      name: 'Twitter',
      href: SOCIAL.TWITTER,
      icon: SocialIcon.TwitterIcon,
    },
    {
      name: 'Slack',
      href: SOCIAL.SLACK,
      icon: SocialIcon.SlackIcon,
    },
    {
      name: 'Discord',
      href: SOCIAL.DISCORD,
      icon: SocialIcon.DiscordIcon,
    },
    {
      name: 'Facebook',
      href: SOCIAL.FACEBOOK,
      icon: SocialIcon.FacebookIcon,
    },
    {
      name: 'GitHub',
      href: SOCIAL.GITHUB,
      icon: SocialIcon.GitHubIcon,
    },
    {
      name: 'LinkedIn',
      href: SOCIAL.LINKEDIN,
      icon: SocialIcon.LinkedInIcon,
    },
    {
      name: 'YouTube',
      href: SOCIAL.YOUTUBE,
      icon: SocialIcon.YouTubeIcon,
    },
  ],
};

export default function Footer() {
  const nextPathname = usePathname();
  const pageCategoryMemo = React.useMemo(() => {
    const category = nextPathname.split('/')[1];
    if (!category) {
      return undefined;
    }
    return category;
  }, [nextPathname]);

  return (
    <footer className="mt-16 bg-darkgrey-900" aria-labelledby="footer-heading">
      <h2 id="footer-heading" className="sr-only">
        Footer
      </h2>

      <div className="mx-auto max-w-7xl px-6 pb-8 pt-16 sm:pt-24 lg:px-8 lg:pt-32">
        <div className="flex flex-col-reverse xl:grid xl:grid-cols-12 xl:gap-8">
          <div className="mt-16 grid grid-cols-2 gap-8 xl:col-span-8 xl:mt-0">
            <div className="md:grid md:grid-cols-2 md:gap-8">
              <FooterCategory label="Products" items={navigation.product} />
              <FooterCategory
                label="Resources"
                items={navigation.resource}
                className="mt-10 md:mt-0"
              />
            </div>
            <div className="md:grid md:grid-cols-2 md:gap-8">
              <FooterCategory label="Company" items={navigation.company} />
            </div>
          </div>

          <div className="col-span-4 mt-10 xl:mt-0">
            <SubscribeForm pageCategory={pageCategoryMemo} />
          </div>
        </div>

        <div className="mt-16 flex flex-col-reverse gap-4 border-t border-white/10 pt-8 sm:mt-20 md:flex-row md:justify-between lg:mt-24">
          <p className="text-xs leading-5 text-gray-400">
            &copy; {`${new Date().getFullYear()}`} PingCAP US, Inc. All Rights
            Reserved. |{' '}
            <NextLink
              href={navigation.legal.privacy.href}
              target="_blank"
              className="hover:text-white"
            >
              {navigation.legal.privacy.name}
            </NextLink>
          </p>
          <SocialIconGroup />
        </div>
      </div>
    </footer>
  );
}

const FooterCategory = (props: {
  className?: string;
  label: string;
  items: {
    name: string;
    href: string;
  }[];
}) => {
  const { label, items, className } = props;

  return (
    <div className={className}>
      <h3 className="text-sm font-bold leading-loose text-darkgrey-400">
        {label}
      </h3>
      <ul role="list" className="mt-6 space-y-2">
        {items.map((item) => (
          <li key={item.name}>
            <NextLink
              href={item.href}
              target="_blank"
              className="text-sm leading-6 text-darkgrey-300 hover:text-white"
            >
              {item.name}
            </NextLink>
          </li>
        ))}
      </ul>
    </div>
  );
};

const SocialIconGroup = (props: any) => {
  return (
    <>
      <div className="flex w-auto flex-wrap items-center gap-4">
        {navigation.social.map((item) => (
          <NextLink
            key={item.name}
            href={item.href}
            target="_blank"
            className="w-fit text-gray-500 hover:text-gray-400"
          >
            <span className="sr-only">{item.name}</span>
            <item.icon className="h-auto max-h-5 w-5" aria-hidden="true" />
          </NextLink>
        ))}
      </div>
    </>
  );
};

const SubscribeForm = (props: { pageCategory?: string }) => {
  const [emailInput, setEmailInput] = React.useState('');
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [tip, setTip] = React.useState<string | undefined | React.ReactNode>(
    undefined,
  );

  const checkIsEmailValid = (email: string) => {
    return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email);
  };

  const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    setTip('');
    setIsSubmitting(true);
    try {
      leadFormSubmitClick({
        page_category: props.pageCategory,
        product_type: 'serverless',
        button_name: 'Subscribe',
        lead_type: 'newsletter_subscription',
        position: 'footer',
      });
      if (!checkIsEmailValid(emailInput)) {
        setTip('Invaild Email.');
        return;
      }
      const result = await submitHSForm('/api/hsforms', {
        email: emailInput,
        ...getQueryParams(),
      });
      if (result?.error) {
        setTip(result.error);
        return;
      }
      leadFormSubmitComplete({
        page_category: props.pageCategory,
        product_type: 'serverless',
        button_name: 'Subscribe',
        lead_type: 'newsletter_subscription',
        position: 'footer',
      });
      const inlineMessage = result.data?.data?.inlineMessage || 'Thanks!';
      console.log(inlineMessage, result.data);
      setTip(
        <div
          dangerouslySetInnerHTML={{
            __html: inlineMessage,
          }}
        />,
      );
    } catch (error: any) {
      console.error(error);
      setTip(error?.toString() || error?.message || 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      <h3 className="inline-flex items-center text-base font-bold leading-6">
        <TiDBCloudIcon className="mr-4 h-10 w-auto" />
        NEWSLETTER
      </h3>
      <p className="mt-2 text-sm leading-8">
        Subscribe to our monthly newsletter, get the latest TiDB updates in your
        inbox
      </p>
      <form className="mt-6 sm:flex sm:max-w-md">
        <label htmlFor="email-address" className="sr-only">
          Email address
        </label>
        <input
          type="email"
          name="email-address"
          id="email-address"
          autoComplete="email"
          required
          className="w-full min-w-0 appearance-none rounded-md border-0 bg-white/5 px-3 py-1.5 text-base text-white shadow-sm ring-1 ring-inset ring-white/10 placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-indigo-500 sm:w-64 sm:text-sm sm:leading-6 xl:w-full"
          placeholder="Enter your email"
          value={emailInput}
          onChange={(event) => {
            setEmailInput(event.target.value);
          }}
        />
        <div className="mt-4 sm:ml-4 sm:mt-0 sm:flex-shrink-0">
          <button
            type="submit"
            className="flex w-full items-center justify-center rounded-md px-3 py-2 text-sm font-semibold text-white shadow-sm hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-500"
            style={{ background: 'var(--Button-Gradient)' }}
            onClick={handleClick}
            disabled={isSubmitting}
          >
            {isSubmitting && <Spinner className="mr-3 h-5 w-5 animate-spin" />}
            Subscribe
          </button>
        </div>
      </form>
      <div className="text-xs text-darkgrey-300">{tip}</div>
    </>
  );
};
