import React, { useState, useContext } from 'react';
import axios from 'axios';
import ecreIcons from '../../components/core/icons';
import { FrontendContext } from '../App/FrontendContext';
import Loader from '../../components/core/Loader';
import { translate } from '../../Helper';

function ShareEmail() {
    const { loadingSettings, settings, referralCoupon } = useContext(FrontendContext);

    if (loadingSettings) {
        return <Loader />;
    }

    const [email, setEmail] = useState('');
    const [name, setName] = useState('');
    const [errors, setErrors] = useState({ email: '', name: '' });

    const validateEmail = (email) => {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(String(email).toLowerCase());
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        let hasErrors = false;

        // Validate email
        if (!email) {
            setErrors((prevErrors) => ({ ...prevErrors, email: translate('email_is_required')  }));
            hasErrors = true;
        } else if (!validateEmail(email)) {
            setErrors((prevErrors) => ({ ...prevErrors, email: translate('invalid_email_format')}));
            hasErrors = true;
        } else {
            setErrors((prevErrors) => ({ ...prevErrors, email: '' }));
        }

        // Validate name
        if (!name) {
            setErrors((prevErrors) => ({ ...prevErrors, name: translate('name_is_required') }));
            hasErrors = true;
        } else {
            setErrors((prevErrors) => ({ ...prevErrors, name: '' }));
        }

        if (hasErrors) return;

        const data = new FormData();
        data.append('action', 'ecre_send_invite_email');
        data.append('email', email);
        data.append('name', name);
        data.append('nonce', ecreFrontend.nonce);

        fetch(ecreFrontend.ajaxurl, {
            method: 'POST',
            body: data,
        })
            .then(response => response.json())
            .then(response => {
                if ('success' == response) {
                    Siz.success( translate('email_send_succesfully'), 4000)
                    setEmail('');
                    setName('');
                } else {
                    Siz.error( translate('opps') , translate('something_went_wrong') )
                }
            })
            .catch(error => {
                console.error('There was an error sending the email:', error);
            });
    };

    return (
        <div className="share-email ecre-mb-4">
            {ecreFrontend.is_user_logged_in ? (
                (settings.canRefferOthers && ecreFrontend.has_orders) || !settings.canRefferOthers ? (
                    <>
                        <h6 className="ecre-text-gray-600 ecre-text-sm ecre-font-normal ecre-mb-2.5">{translate('share_via_email')}</h6>
                        <form className="share-email__form ecre-text-center" onSubmit={handleSubmit}>
                            <div className="ecre-mb-2.5">
                                <input
                                    type="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    placeholder={translate('friend_email')}
                                    className={`!ecre-text-[#4A4A4A] placeholder:!ecre-text-[#A49DA7] !ecre-shadow-none !ecre-text-xs !ecre-font-normal !ecre-bg-white !ecre-p-2.5 !ecre-w-full !ecre-rounded-lg !ecre-border !ecre-border-solid !ecre-border-[#EDE8F1] focus:!ecre-border-solid focus:!ecre-border-violet-200 focus-visible:!ecre-outline-0 ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? '!ecre-opacity-50 !ecre-cursor-not-allowed' : ''}`}
                                    disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                                />
                                {errors.email && <div className="ecre-text-red-500 ecre-text-xs ecre-mt-1">{errors.email}</div>}
                            </div>
                            <div className="ecre-mb-2.5">
                                <input
                                    type="text"
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                    placeholder={translate('friend_name')}
                                    className={`!ecre-text-[#4A4A4A] placeholder:!ecre-text-[#A49DA7] !ecre-shadow-none !ecre-text-xs !ecre-font-normal !ecre-bg-white !ecre-p-2.5 !ecre-w-full !ecre-rounded-lg !ecre-border !ecre-border-solid !ecre-border-[#EDE8F1] focus:!ecre-border-solid focus:!ecre-border-violet-200 focus-visible:!ecre-outline-0 ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? '!ecre-opacity-50 !ecre-cursor-not-allowed' : ''}`}
                                    disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                                />
                                {errors.name && <div className="ecre-text-red-500 ecre-text-xs ecre-mt-1">{errors.name}</div>}
                            </div>
                            <button
                                type="submit"
                                className={`ecre-group ecre-w-[89px] ecre-h-[35px] !ecre-px-2 !ecre-py-[5px] !ecre-bg-white ecre-cursor-pointer ecre-rounded-[5px] ecre-border ecre-border-solid !ecre-border-violet-600 !ecre-text-violet-600 !ecre-text-xs ecre-font-normal !ecre-inline-flex ecre-items-center ecre-justify-center ecre-gap-1 ecre-transition hover:!ecre-bg-violet-600 focus:!ecre-bg-violet-600 hover:!ecre-text-white focus:!ecre-text-white ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}
                                disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                            >
                                <span className="icon">
                                    {ecreIcons.sendEmail}
                                </span>
                                <span>{translate('send')}</span>
                            </button>
                        </form>

                    </>
                ) : (
                <div className="ecre-mt-6">
                    <div className="icon ecre-flex ecre-justify-center ecre-mb-4">
                        {ecreIcons.noOrder}
                    </div>
                    <div className="ecre-text-[#5e656a] ecre-text-xs ecre-font-normal ecre-leading-[18px]">
                        <p className='ecre-text-center'>{settings.noOrderMessageToReferrer}</p>
                    </div>
                </div>
                )
            ) : (
                <div>
                    <h3 className="ecre-text-neutral-950 ecre-text-[35px] !ecre-mt-0 ecre-font-medium ecre-mb-2">{translate('refer_and_win_exciting_rewards')}</h3>
                    <p className="ecre-text-[#686977] ecre-mb-5 ecre-text-xs ecre-font-normal">{translate('create_account_get_referral_code')}</p>
                    <button className="ecre-px-2.5 ecre-inline-flex ecre-items-center !ecre-shadow-none ecre-py-2.5 !ecre-bg-[#6d3ae6] ecre-cursor-pointer ecre-border-0 ecre-rounded-[5px] ecre-text-white ecre-text-[10px] ecre-font-normal ecre-transition hover:!ecre-bg-violet-800"
                    onClick={() => {
                        const siteUrl = ecreFrontend.site_url;
                        window.location.href = `${siteUrl}/my-account/`;
                    }}
                    >
                        <span className="icon ecre-mr-1">
                            {ecreIcons.loginGift}
                        </span>
                        {translate('get_rewards_now')}
                    </button>
                </div>
            )}


        </div>
    );
}

export default ShareEmail;
