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

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

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

    const [elSettings, setElSettings] = useState(settings_mx || {});
    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 ecre-share-email">
            {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">{elSettings.title || 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-[#A49DA7] 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 ${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-[#A49DA7] 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 ${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-rounded-[5px] ecre-border !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 hover: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}
                                style={{
                                    backgroundColor: elSettings.inviteBtnBg || '#fff',
                                    color: elSettings.inviteBtnTextColor || '#6d3ae6',
                                    borderColor: elSettings.inviteBtnBorderClr || '#6d3ae6',
                                }}

                                onMouseOver={(e) => {
                                    e.currentTarget.style.backgroundColor = elSettings.inviteBtnHBg || '#6D3AE6';
                                    e.currentTarget.style.color = elSettings.inviteBtnTextHColor || '#fff';
                                    e.currentTarget.style.borderColor = elSettings.inviteBtnBorderHClr || '#6d3ae6';
                                    const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                    svgPaths.forEach(path => path.style.fill = elSettings.inviteBtnSvgHClr || '#fff');
                                }}

                                onMouseOut={(e) => {
                                    e.currentTarget.style.backgroundColor = elSettings.inviteBtnBg || '#fff';
                                    e.currentTarget.style.color = elSettings.inviteBtnTextColor || '#6d3ae6';
                                    e.currentTarget.style.borderColor = elSettings.inviteBtnBorderClr || '#6d3ae6';

                                    const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                    svgPaths.forEach(path => path.style.fill = elSettings.inviteBtnSvgClr || '#6d3ae6');
                                }}
                            >
                                <span className="icon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="11" viewBox="0 0 12 11" fill="none">
                                        <path className=" transition group-hover:fill-white" d="M8.02116 7.52714L11.2333 4.36785L11.274 4.32142C11.3343 4.24049 11.3634 4.14053 11.3559 4.03989C11.3484 3.93926 11.3049 3.8447 11.2333 3.77356L8.02116 0.615701L7.97687 0.577844C7.71973 0.384986 7.34116 0.570701 7.34116 0.912844V2.43427L7.18044 2.44499C4.63544 2.64642 3.14472 4.25713 2.78901 7.17857C2.7433 7.55357 3.1733 7.78857 3.45187 7.54C4.47401 6.62714 5.53044 6.05999 6.62687 5.83285C6.80259 5.79642 6.97902 5.76857 7.15687 5.74928L7.34116 5.73285V7.23L7.34473 7.28857C7.38759 7.61214 7.77973 7.76428 8.02116 7.52714ZM7.23259 3.15713L8.05545 3.10213V1.64999L10.5169 4.06999L8.05545 6.49142V4.95071L7.08687 5.03785H7.08116C5.86473 5.16856 4.71687 5.65571 3.6333 6.46785C3.84615 5.51142 4.20973 4.79214 4.68758 4.27713C5.28044 3.63785 6.10901 3.24713 7.23259 3.15713ZM2.42829 1.21427C1.95469 1.21427 1.50049 1.40241 1.1656 1.7373C0.830716 2.07218 0.642578 2.52639 0.642578 2.99999V8.71428C0.642578 9.18788 0.830716 9.64209 1.1656 9.97698C1.50049 10.3119 1.95469 10.5 2.42829 10.5H8.14259C8.61619 10.5 9.07039 10.3119 9.40528 9.97698C9.74017 9.64209 9.9283 9.18788 9.9283 8.71428V8C9.9283 7.90528 9.89068 7.81444 9.8237 7.74746C9.75672 7.68048 9.66588 7.64285 9.57116 7.64285C9.47644 7.64285 9.3856 7.68048 9.31862 7.74746C9.25165 7.81444 9.21402 7.90528 9.21402 8V8.71428C9.21402 8.99844 9.10114 9.27097 8.9002 9.4719C8.69927 9.67283 8.42675 9.78571 8.14259 9.78571H2.42829C2.14413 9.78571 1.87161 9.67283 1.67068 9.4719C1.46975 9.27097 1.35686 8.99844 1.35686 8.71428V2.99999C1.35686 2.71583 1.46975 2.44331 1.67068 2.24237C1.87161 2.04144 2.14413 1.92856 2.42829 1.92856H4.57115C4.66588 1.92856 4.75672 1.89093 4.82369 1.82395C4.89067 1.75698 4.9283 1.66614 4.9283 1.57142C4.9283 1.4767 4.89067 1.38586 4.82369 1.31888C4.75672 1.2519 4.66588 1.21427 4.57115 1.21427H2.42829Z" style={{ fill: elSettings.inviteBtnSvgClr || "#6d3ae6", }} />
                                    </svg>
                                </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 ShareEmailBlock;
