"use client";

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from "@hookform/resolvers/yup";
import { learnMoreValidationSchema } from "@/utils/form";
import { LearnMoreForm, ModalStatus, SourceModal } from '@/types';
import { mailchimp } from "@/app/(auth)/actions";
import { toast } from 'react-toastify';

interface ModalLearnMoreFormProps {
    setStatus: React.Dispatch<React.SetStateAction<ModalStatus>>;
}

const ModalLearnMoreForm = ({ setStatus }: ModalLearnMoreFormProps) => {
    const [email, setEmail] = useState("");

    const { register, handleSubmit, reset, formState: {errors} } = useForm({
      resolver: yupResolver(learnMoreValidationSchema),
    });

    const submitForm = async (data: LearnMoreForm) => {
      setEmail(data.email);
      if (!data.email) {
          return;
      }
      setStatus(ModalStatus.Loading);
      
      try{
          await sendMailchimpRequest(data);
          setEmail("");
          reset();
        //   await handleSendgridSubmit(data.email);
          setStatus(ModalStatus.Success);
      } catch(error) {
          if (error instanceof Error){
          toast.error(error.message, {
              position: "bottom-left",
              autoClose: 5000,
              hideProgressBar: false,
              closeOnClick: true,
              pauseOnHover: true,
              draggable: true,
              progress: undefined,
              theme: "colored",
              });
          }
          setStatus(ModalStatus.Default);
      }
    }

    const sendMailchimpRequest = async (data: LearnMoreForm) => {
        console.log("sendMailchimpRequest call initiated");
        await mailchimp({
            email: data.email,
            first_name: '',
            last_name: '',
            phone_number: '',
            company_size: '',
            source: SourceModal.LearnMore,
        });
        console.log("sendMailchimpRequest call success");
    };

    const handleSendgridSubmit = async (email: string) => {
    
        const data = {
          subscriberEmail: email,
        };
        //call to the Netlify Function you created
        return fetch("./.netlify/functions/triggerLearnMoreEmail", {
          method: "POST",
          body: JSON.stringify({
            subscriberEmail: data.subscriberEmail,
          }),
        });
    };

    return (

        <form onSubmit={handleSubmit(submitForm)} className="w-full md:w-1/2">
            <div className='relative mt-3 mb-2'>
                <input {...register("email")} id="learnMoreEmail" type='text' className="w-full appearance-none bg-transparent border border-white focus:border-white rounded-sm px-4 mr-2 text-white placeholder-white" placeholder="Your best email…" aria-label="Your best email…" autoComplete="on" />
                <label className='md:absolute top-[50%] translate-y-[-50%] left-[105%] w-[220px] text-red-400' htmlFor='learnMoreEmail'>{errors.email ? "*" + errors.email.message : ""}</label>
            </div>

            <button type="submit" className="btn capitalize font-bold text-black bg-white hover:bg-white shadow">Submit</button>
        </form>

    );
};

export default ModalLearnMoreForm;