"use client";

import React, { useState } from 'react';
import { NewsLetterForm, SourceModal } from '@/types';
import { mailchimp } from "@/app/(auth)/actions";
import { toast } from 'react-toastify';
import { ModalStatus } from '@/types';
import IconLoading from '@/images/IconLoading';
import Button from '@/components/Button';

const NewsletterForm = () => {

    const [status, setStatus] = useState<ModalStatus>(ModalStatus.Default);
    const [email, setEmail] = useState('');

    const submitForm = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        try{
            if (!email) {
                throw Error("Email is Empty");
            }
            if (email.indexOf("@") === -1) {
                throw Error("Email is invalid");
            }
            setStatus(ModalStatus.Loading);
            const formData = {
                email: email,
                first_name: '',
                last_name: '',
                phone_number: '',
                company_size: '',
                source: SourceModal.Newsletter,
            }
            await sendMailchimpRequest(formData);
            // await handleSendgridSubmit(formData.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: NewsLetterForm) => {
        console.log("sendMailchimpRequest call initiated");
        await mailchimp({
            email: data.email,
            first_name: '',
            last_name: '',
            phone_number: '',
            company_size: '',
            source: data.source,
        });
        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 (

        <>
            <div className="mb-6 lg:mr-16 lg:mb-0 text-center lg:text-left lg:w-1/2">
                <h3 className="h3 text-white mb-2">{status !== ModalStatus.Success ? "Stay Ahead of the Curve" : "Thanks for subscribing"}</h3>
                <p className="text-white text-lg">{status !== ModalStatus.Success ? "Join our newsletter to get top news before anyone else." : "You are going to love what we have to show you"}</p>
            </div>

            <div className="w-full lg:w-1/2">
                <form onSubmit={(e) => submitForm(e)} className="flex flex-col sm:flex-row justify-center max-w-xs mx-auto sm:max-w-md lg:max-w-none">
                <input 
                    required 
                    name="email" 
                    type="email" 
                    onChange={event => setEmail(event.target.value)} 
                    value={email} 
                    className="w-full appearance-none bg-transparent border border-white focus:border-white rounded-sm px-4 py-3 mb-2 sm:mb-0 sm:mr-2 text-white placeholder-white disabled:bg-transparent" 
                    placeholder="Your best email…" 
                    aria-label="Your best email…" 
                    disabled={status === ModalStatus.Success}
                    autoComplete="on"
                />
                <Button status={status} text={(() => {
                    switch (status) {
                        case ModalStatus.Loading:
                            return "Sending...";
                        case ModalStatus.Success:
                            return "Success";
                        case ModalStatus.Default:
                            return "Subscribe";
                        default:
                            return "default-class";
                    }
                })()}/>
                </form>
            </div>

        </>

    );
};

export default NewsletterForm;