'use client';

import * as React from 'react';
import NextLink from 'next/link';

import { Spinner, CheckIcon, QuestionIcon } from '@/components/Icon';
import { PopoverTooltip } from '@/app/ai/_components/Tooltip';
import { PRIVACY, TIDB_AI_PRIVATE_BETA_TYPEFORM } from '@/constant/url';
import { submitHSForm } from '@/lib/hsForm';
import { leadFormSubmitClick, leadFormSubmitComplete } from '@/components/GTM';
import { getQueryParams } from '@/utils';

export default function SubscribeInput() {
  const [emailInput, setEmailInput] = React.useState('');
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [tip, setTip] = React.useState<string | undefined | React.ReactNode>(
    undefined,
  );
  const [isSubmitted, setIsSubmitted] = React.useState(false);

  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: 'ai',
        product_type: 'serverless',
        button_name: 'Join The Waitlist',
        lead_type: 'waitlist',
        position: 'waitlist',
      });
      if (!checkIsEmailValid(emailInput)) {
        setTip('Invaild Email.');
        return;
      }
      const result = await submitHSForm('/api/hsforms/ai/private-beta', {
        email: emailInput,
        ...getQueryParams()
      });
      if (result?.error) {
        setTip(result.error);
        return;
      }
      leadFormSubmitComplete({
        page_category: 'ai',
        product_type: 'serverless',
        button_name: 'Join The Waitlist',
        lead_type: 'waitlist',
        position: 'waitlist',
      });
      const inlineMessage = result.data?.data?.inlineMessage || 'Thanks!';
      console.log(inlineMessage, result.data);
      setIsSubmitted(true);
    } catch (error: any) {
      console.error(error);
      setTip(error?.toString() || error?.message || 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isSubmitted) {
    return (
      <div className="rounded-xl bg-black p-6">
        <div className="flex gap-3">
          <CheckIcon className="my-1 h-5 w-5 text-success" />
          <div className="text-sm font-normal leading-6 text-white">
            <div>Thank you for joining our private beta waitlist!</div>
            <div>We will notify you when the private beta is ready.</div>
            <br />
            <div>
              Want to get ahead in the queue?{' '}
              <NextLink
                href={TIDB_AI_PRIVATE_BETA_TYPEFORM + '#email=' + emailInput}
                target="_blank"
                className="text-[#0CA6F2] underline"
              >
                Take a 2 minutes survey
              </NextLink>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center gap-2">
        <form
          className="flex w-full flex-col items-center justify-between gap-4 rounded-md border-[3px] bg-[#212121] p-2 md:w-fit md:flex-row"
          style={{
            // borderImage: 'var(--Ad-bar-Gradient) 3 rounded',
            borderColor: '#1E4048',
          }}
        >
          <input
            type="email"
            placeholder="Enter your email address"
            autoComplete="email"
            className="w-full border-0 bg-transparent px-4 py-1 outline-none ring-0 ring-transparent md:w-auto"
            autoFocus
            value={emailInput}
            onChange={(event) => {
              setEmailInput(event.target.value);
            }}
          />
          <button
            type="submit"
            className="inline-flex w-full items-center justify-center rounded-md border-0 px-4 py-2 text-base font-medium text-white md:w-auto"
            style={{
              background:
                'linear-gradient(262deg, #11A5ED 6.22%, #11C5ED 108.36%)',
            }}
            onClick={handleClick}
            disabled={isSubmitting}
          >
            {isSubmitting && <Spinner className="mr-3 h-5 w-5 animate-spin" />}
            Join The Waitlist
          </button>
        </form>
        {/* <div className='has-tooltip'><QuestionIcon /></div> */}
        <PopoverTooltip
          className="relative min-w-[200px] rounded-lg border border-darkgrey-800 bg-background p-4 text-sm text-darkgrey-500 shadow-lg"
          content={
            <>
              By providing your email, you consent to TiDB processing your
              personal information as detailed in our{' '}
              <NextLink href={PRIVACY} target="_blank" className="underline">
                Privacy Policy
              </NextLink>
              .
            </>
          }
        >
          <QuestionIcon className="h-4 w-4 text-darkgrey-500" />
        </PopoverTooltip>
      </div>
      <div className="text-xs text-danger">{tip}</div>
      <p className="mt-2 text-xs font-normal text-darkgrey-500">
        * Join with confidence - we respect your inbox and won&apos;t spam you.{' '}
      </p>
    </>
  );
}
