import React, { useState, useEffect } from 'react';
import Tooltip from '../../../components/core/Tooltip';
import ecreIcons from '../../../components/core/icons';
import Modal from '../../../components/core/Modal';
import { displayProPopup } from '../../../Helper';
import { translate } from '../../../Helper';

const ImageUploader = ({ imageUrl, setImageUrl, label, uploaderTitle, uploaderBtnText, tooltip, isPro = true }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [mouseHover, setMouseHover] = useState(false);

    const handleMouseEnter = () => {
        setMouseHover(true);
    };
  
    const handleMouseLeave = () => {
        setMouseHover(false);
    };

    const handleToggleModal = () => {
        setIsOpen(!isOpen);
    };

    // Ensure wp.media exists before calling it
    useEffect(() => {
        if (!window.wp || !window.wp.media) {
            console.error('WordPress media library is not available.');
        }
    }, []);

    const openMediaUploader = (event) => {
        event.preventDefault(); // Prevent default behavior
        event.stopPropagation(); // Stop event bubbling

        if (!window.wp || !window.wp.media) {
            console.error('WordPress media library is not loaded.');
            return;
        }

        const customUploader = window.wp.media({
            title: uploaderTitle,
            button: {
                text: uploaderBtnText,
            },
            multiple: false,
        });

        customUploader.on('select', () => {
            const attachment = customUploader.state().get('selection').first().toJSON();
            setImageUrl(attachment.url); // Set the image URL
        });

        customUploader.open();
    };

    const resetImage = () => {
        setImageUrl('');
        setIsOpen(false);
    };

    return (
        <>
            <div className={`ecre-w-full ${ !isPro && mouseHover ? "pro-lock-hover" : "" }`}>
                <label
                    onClick={!isPro ? displayProPopup : undefined}
                    className="ecer-image-uploader ecre-text-gray-900 ecre-text-sm ecre-font-medium ecre-inline-block ecre-mb-2"
                >
                    <span className={`ecre-mr-2.5 ${!isPro ? 'ecre-opacity-50' : ''}`}>{label}</span>
                    <Tooltip className="ecre-align-[-2px]" content={tooltip} />
                    {!isPro && (
                        <button className='ecre-px-1.5 btn-prolock ecre-border-0 ecre-inline-flex ecre-items-center ecre-pt-[3px] ecre-pb-[4px] ecre-bg-[#fee8fd] ecre-rounded-[26px] ecre-text-[#4d1c4b] ecre-text-sm ecre-font-normal '>
                            <span className="icon-wrap">
                                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="11" viewBox="0 0 13 11" fill="none">
                                    <path d="M0.806113 7.65309C0.542977 5.94268 0.279841 4.23232 0.0167049 2.52191C-0.0416496 2.14276 0.389758 1.88417 0.696628 2.11434C1.51645 2.7292 2.33622 3.34402 3.15604 3.95889C3.42597 4.16133 3.81053 4.09545 3.99766 3.81471L6.04517 0.743421C6.26154 0.41886 6.73842 0.41886 6.95479 0.743421L9.0023 3.81471C9.18944 4.09545 9.574 4.16129 9.84392 3.95889C10.6637 3.34402 11.4835 2.7292 12.3033 2.11434C12.6102 1.88417 13.0416 2.14276 12.9833 2.52191C12.7202 4.23232 12.457 5.94268 12.1939 7.65309H0.806113Z" fill="#F748F0" />
                                    <path d="M11.6001 10.5H1.39974C1.07185 10.5 0.80603 10.2342 0.80603 9.90627V8.60205H12.1938V9.90627C12.1938 10.2342 11.9279 10.5 11.6001 10.5Z" fill="#F748F0" />
                                </svg>
                            </span>
                            <span className="text">{translate('upgrade')}</span>
                        </button>
                    )}
                </label>

                <div className="ecre-flex ecre-flex-wrap ecre-gap-4 ecre-mb-2">
                    <div
                        className={`upload-field ${!isPro && 'ecre-opacity-50'}`}
                        onClick={!isPro ? displayProPopup : undefined}
                        onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}
                    >
                        <div className="upload-file ecre-relative" >
                            <button
                                id="upload-menu-icon"
                                className={`file:ecre-hidden !ecre-text-gray-900 !ecre-shadow-none !ecre-text-sm ecre-bg-white ecre-pl-[60px] ecre-pr-[15px] ecre-py-[15px] ecre-w-full ecre-max-w-[320px] ecre-rounded-lg ecre-border ecre-border-solid ecre-border-[#9CA3AF] !ecre-outline-none ecre-text-left ${!isPro ? 'ecre-bg-gray-200' : ''}`}
                                onClick={!isPro ? displayProPopup : openMediaUploader}
                            >
                                {translate('choose_file_to_upload')}
                            </button>
                            <label
                                htmlFor="upload-menu-icon"
                                className="ecre-absolute ecre-cursor-pointer ecre-top-2 ecre-left-4 ecre-w-9 ecre-h-9 ecre-bg-violet-50 ecre-rounded-sm ecre-flex ecre-justify-center ecre-items-center"
                                disabled={!isPro}
                            >
                                {ecreIcons.upload}
                            </label>
                        </div>
                        <p className="ecre-text-gray-500 ecre-text-xs ecre-mt-2">{translate('supported_format')}</p>
                    </div>

                    {imageUrl && isPro && (
                        <div className="uploaded-icon">
                            <div className="uploaded-icon__menu ecre-w-[60px] ecre-h-[52px] ecre-bg-white ecre-rounded-lg ecre-overflow-hidden ecre-border ecre-border-solid ecre-flex ecre-justify-center ecre-items-center">
                                <img src={imageUrl} alt="Uploaded Icon" className="ecre-w-full ecre-h-full ecre-object-cover" />
                            </div>
                            <button
                                onClick={handleToggleModal}
                                className="ecre-text-red-500 ecre-text-xs ecre-m-0 ecre-p-0 ecre-mt-2 !ecre-bg-transparent !ecre-border-0 !ecre-cursor-pointer !ecre-outline-0 !ecre-shadow-none"
                            >
                                {translate('reset_icon')}
                            </button>
                        </div>
                    )}
                </div>
            </div>

            <Modal openModal={isOpen} toggleModal={handleToggleModal}>
                {{
                    header: <h6 className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('want_to_reset_icon')}</h6>,
                    body: <p className="ecre-text-gray-900 ecre-text-sm">{translate('reset_desc')}</p>,
                    footer: (
                        <div className="btn-box ecre-justify-end ecre-flex ecre-gap-2">
                            <button
                                onClick={handleToggleModal}
                                className="ecre-text-gray-900 ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-bg-slate-100 ecre-rounded-lg ecre-border ecre-border-solid ecre-border-slate-100 hover:ecre-border-red-500 hover:ecre-bg-white hover:ecre-text-red-500"
                            >
                                {translate('cancel')}
                            </button>

                            <button
                                onClick={resetImage}
                                className="ecre-text-white ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-border ecre-border-solid ecre-border-red-500 ecre-bg-red-500 ecre-rounded-lg hover:ecre-bg-white hover:ecre-text-red-500"
                            >
                                {translate('confirm')}
                            </button>
                        </div>
                    ),
                }}
            </Modal>
        </>
    );
};

export default ImageUploader;
