import { useMutation } from '@tanstack/react-query';
import { Formik } from 'formik';
import { AuthModalState } from './AuthModal';
import { EMAIL_REGEX, getRecaptchaToken } from './helper';
import { AuthButton, FieldWrapper, FormField, FormFieldError, FormLabel, FormWrapper, Notice } from './styles';
import { useState } from 'react';
import Link from 'next/link';
import trackAnalyticsEvent from '@/lib/trackAnalyticsEvent';

const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;

const ForgotForm = ({ setAuthModalState }: { setAuthModalState: (state: AuthModalState) => void }) => {
  interface Values {
    email: string;
  }

  const { mutate, isLoading, isError, isSuccess } = useMutation(async (values: Values) => {
    const { email } = values;
    const token = await getRecaptchaToken('forgot_password');

    const response = await fetch(`${SERVER_URL}/auth/email/forgot`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, token }),
      credentials: 'include',
    });

    if (response.status !== 200) {
      throw new Error('Something went wrong');
    }
  }, {});

  const validate = (values: Values) => {
    const errors: Partial<Values> = {};
    if (!values.email) {
      errors.email = 'Required';
    } else if (!EMAIL_REGEX.test(values.email)) {
      errors.email = 'Invalid email address';
    }
    return errors;
  };

  return (
    <Formik
      initialValues={{
        email: '',
      }}
      validateOnBlur={false}
      validate={validate}
      onSubmit={(values) => mutate(values)}
    >
      <FormWrapper>
        <br />
        <FieldWrapper>
          <div className="labelWrapper">
            <FormLabel htmlFor="email">Email</FormLabel>
            <FormFieldError name="email" component="div" />
          </div>
          <FormField disabled={isSuccess || isLoading} id="email" name="email" placeholder="email" type="text" />
        </FieldWrapper>
        <AuthButton disabled={isSuccess || isLoading} type="submit" style={{ marginTop: 0, marginBottom: '0.5rem' }}>
          {isLoading ? (
            <>Loading...</>
          ) : isSuccess ? (
            <>
              Sent Reset Email <span style={{ fontSize: '1.5rem' }}>✅</span>
            </>
          ) : (
            <>
              Send Reset Email
              <img src="/images/icons/Email.svg" height={24} width={24} alt="Email Icon" />
            </>
          )}
        </AuthButton>
        {isSuccess && (
          <Notice className="flash">
            If an account with that email exists,
            <br />
            you'll receive an email soon.
            <br />
            <br />
            (Check your spam folder if you don't see it!)
          </Notice>
        )}
        {isError && <Notice className="flash">Something went wrong. Please try again.</Notice>}
      </FormWrapper>
    </Formik>
  );
};

export default ForgotForm;
