import {Tooltip} from "react-tooltip";
import SettingsContext from "../../contexts/SettingsContext";
import Header from "./Header";
import SelectImage from "../LiveEdit/SelectImage";
import LiveEditButton from "./LiveEditButton";
import {imageReplacements} from "../../includes/functions";
import {showProModal} from "../ProModal";

const {FormToggle, RangeControl} = wp.components;
const {useRef, useContext, useState, useEffect} = React;

export default function Images() {
    const {isPro} = dracula;

    const context = useContext(SettingsContext);
    const {data, setData, isLiveEdit} = context;

    const {
        darkenBackgroundImages = true,
        darkenBackgroundImagesLevel = 60,

        images = [{}],
        lowBrightnessImages = true,
        lowBrightnessLevel = 80,
        grayscaleImages,
        grayscaleImagesLevel = 80,
        invertImages,
        invertImagesLevel = 80,
    } = data;

    const [innerTab, setInnerTab] = useState('img-replacement');

    const [currentItem, setCurrentItem] = useState(null);

    const frameRef = useRef();

    const updateImage = (index, type, image) => {
        setCurrentItem(index);

        setData({
            ...data,
            images: [...images.slice(0, index), {...images[index], [type]: image}, ...images.slice(index + 1)]
        });
    }

    const selectImage = (index, type) => {

        if (frameRef.current) {
            frameRef.current.off('select');

            frameRef.current.on('select', () => {
                const attachment = frameRef.current.state().get('selection').first().toJSON();
                updateImage(index, type, attachment.url);

            }).open();
            return;
        }

        frameRef.current = wp.media({
            title: wp.i18n.__('Select Image', 'dracula-dark-mode'),
            button: {text: wp.i18n.__('Select Image', 'dracula-dark-mode'),},
            library: {type: 'image'},
            multiple: false
        });

        frameRef.current.on('select', () => {
            const attachment = frameRef.current.state().get('selection').first().toJSON();
            updateImage(index, type, attachment.url);
        }).open();
    }

    const removeGroup = (index) => {
        const newImages = [...images.slice(0, index), ...images.slice(index + 1)];

        setData({...data, images: newImages});

        if (isLiveEdit) {
            imageReplacements(newImages, true);
        }
    }

    console.log(images);
    window.images = images;

    return (
        <div className="dracula-settings-content">
            <Header title={wp.i18n.__('Images Settings', 'dracula-dark-mode')}/>

            {/* tab */}
            <div className="inner-tabs">
                <button type="button"
                        className={`tab-item dracula-btn ${innerTab === 'img-replacement' ? 'active' : ''}`}
                        onClick={() => setInnerTab('img-replacement')}>
                    <span className="dracula-btn-icon icon-img-replacement"></span>
                    <span>{wp.i18n.__('Image Replacement', 'dracula-dark-mode')}</span>
                </button>

                <button type="button" className={`tab-item dracula-btn ${innerTab === 'img-behavior' ? 'active' : ''}`}
                        onClick={() => setInnerTab('img-behavior')}>
                    <span className="dracula-btn-icon icon-img-behavior"></span>
                    <span>{wp.i18n.__('Image Behavior', 'dracula-dark-mode')}</span>
                </button>
            </div>

            {'img-replacement' == innerTab &&
                <>
                    {/* Image Replacement */}
                    <div className={`settings-field field-image-replacement`}>

                        <div className="settings-field-content">

                            <div className="image-replacements">
                                <h3>{wp.i18n.__('Image Replacement', 'dracula-dark-mode')}</h3>

                                {!isLiveEdit &&
                                    <>
                                        <p>{wp.i18n.__('Replace specific images when dark mode is enabled.', 'dracula-dark-mode')}</p>
                                        <div className="image-replacements-header-group">
                                            <div className="group-item">
                                                <div className={`group-item-header`}>
                                                    <span
                                                        className={`header-title`}>{wp.i18n.__('Light Mode Images', 'dracula-dark-mode')}</span>
                                                    <p>{wp.i18n.__('Enter the image links or select the images that are shown in the light mode.', 'dracula-dark-mode')}</p>
                                                </div>
                                            </div>

                                            <div className="group-item">
                                                <div className={`group-item-header`}>
                                                    <span
                                                        className={`header-title`}>{wp.i18n.__('Dark Mode Images', 'dracula-dark-mode')}</span>
                                                    <p>{wp.i18n.__('Enter the image links or select the images that will be displayed in the dark mode replacing the light images.', 'dracula-dark-mode')}</p>
                                                </div>
                                            </div>

                                            <button type={`button`}
                                                    className="dracula-btn input-group-append zero-opacity">
                                                <span className="dracula-btn-icon icon-add-image"></span>
                                            </button>
                                        </div>
                                    </>
                                }

                                {images.map((image, index) => {
                                    const lightImage = image.light;
                                    const darkImage = image.dark;
                                    const currentLightImage = lightImage ? lightImage : `${dracula.pluginUrl}/assets/images/settings/img-placeholder.svg`;
                                    const currentDarkImage = darkImage ? darkImage : `${dracula.pluginUrl}/assets/images/settings/img-placeholder.svg`;
                                    return (
                                        <div
                                            className="image-replacements-group"
                                            onClick={() => {
                                                if (images?.length > 1 && !isPro) {
                                                    showProModal();
                                                }
                                            }}
                                            key={index}
                                        >
                                            {/* Light Mode Images */}
                                            <div className="group-item">
                                                <div className="input-group">

                                                    <div className={`img-preview ${lightImage ? '' : 'placeholder'}`}>
                                                        <img src={currentLightImage} alt=""/>
                                                    </div>

                                                    <input type="url" placeholder="Enter light mode image link"
                                                           value={lightImage}
                                                           onChange={e => updateImage(index, 'light', e.target.value)}/>

                                                    {!!isLiveEdit && 'classic' !== isLiveEdit &&
                                                        <SelectImage
                                                            index={index}
                                                            data={data}
                                                            setData={setData}
                                                            setCurrentItem={setCurrentItem}
                                                        />
                                                    }

                                                    <button
                                                        type={`button`}
                                                        className="dracula-btn input-group-append"
                                                        onClick={() => {
                                                            selectImage(index, 'light');
                                                        }}
                                                    >
                                                        <span className="dracula-btn-icon icon-add-image"></span>
                                                        <span>{wp.i18n.__('Browse', 'dracula-dark-mode')}</span>
                                                    </button>
                                                </div>
                                            </div>

                                            {/* Dark Mode Images */}
                                            <div className="group-item">
                                                <div className="input-group">
                                                    <div
                                                        className={`img-preview dark ${darkImage ? '' : 'placeholder'}`}>
                                                        <img src={currentDarkImage} alt=""/>
                                                    </div>

                                                    <input type="url" placeholder="Enter dark mode image link"
                                                           value={darkImage}
                                                           onChange={e => updateImage(index, 'dark', e.target.value)}/>

                                                    <button type={`button`} className="dracula-btn input-group-append"
                                                            onClick={() => selectImage(index, 'dark')}>
                                                        <span className="dracula-btn-icon icon-add-image"></span>
                                                        <span>{wp.i18n.__('Browse', 'dracula-dark-mode')}</span>
                                                    </button>
                                                </div>

                                            </div>

                                            {(index === currentItem && isLiveEdit) ?
                                                <button type={`button`}
                                                        className={`dracula-btn btn-primary ${!isPro ? 'pro-feature' : ''}`}
                                                        onClick={() => {
                                                            if (!isPro) {
                                                                showProModal();
                                                                return;
                                                            }

                                                            setCurrentItem(null);
                                                            if (draculaDarkMode.isEnabled()) {
                                                                imageReplacements(images);
                                                            }
                                                        }}>
                                                    <span>{wp.i18n.__('Update', 'dracula-dark-mode')} </span>
                                                </button>
                                                :
                                                <button
                                                    data-tooltip-content={ ( !isPro && index !== 0) ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                                    data-tooltip-id={`image-replacement-group-remove`}
                                                    type={`button`}
                                                    className={`dracula-btn btn-danger ${!isPro ? 'pro-feature' : ''}`}
                                                    onClick={() => {
                                                        if (!isPro && index !== 0) {
                                                            showProModal();
                                                            return;
                                                        }

                                                        removeGroup(index);
                                                    }}>
                                                    {isLiveEdit
                                                        ? <span>{wp.i18n.__('Remove', 'dracula-dark-mode')} </span>
                                                        : <i className="dashicons dashicons-trash"></i>
                                                    }
                                                </button>
                                            }

                                        </div>
                                    )
                                })}

                                {!isPro && <Tooltip id={`image-replacement-group-remove`} effect="solid" place="left" variant="warning" className={'dracula-tooltip'}/>}

                                <button
                                    data-tooltip-content={( !isPro && images.length >= 1) ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                    data-tooltip-id="image-replacement-group-add"
                                    type={`button`}
                                    className={`dracula-btn btn-primary add-group ${!isPro ? 'pro-feature' : ''}`}
                                    onClick={() => {
                                        if (!isPro && images.length >= 1) {
                                            showProModal();
                                            return;
                                        }
                                        setData({...data, images: [...images, {}]})
                                    }}>
                                    <i className={`dashicons dashicons-plus-alt2`}></i>
                                    <span>{wp.i18n.__('Add New Group', 'dracula-dark-mode')}</span>
                                </button>

                                {!isPro && <Tooltip id={`image-replacement-group-add`} effect="solid" place="right" variant="warning" className={'dracula-tooltip'}/>}

                            </div>

                            {!isLiveEdit && <LiveEditButton tab={`images`}/>}

                        </div>
                    </div>
                </>
            }

            {'img-behavior' == innerTab &&
                <>
                    {/* Darken Background Images */}
                    <div className="settings-field field-darken-background-images">
                        <h4 className={`settings-field-label`}>{wp.i18n.__('Darken Background Images', 'dracula-dark-mode')}</h4>
                        <div className="settings-field-content">

                            <FormToggle
                                checked={darkenBackgroundImages}
                                onChange={() => setData({...data, darkenBackgroundImages: !darkenBackgroundImages})}
                            />

                            <p className={'description'}>{wp.i18n.__(`Darken background images on dark mode to make them more readable.`, 'dracula-dark-mode')}</p>
                        </div>

                        {!!darkenBackgroundImages &&
                            <div className="settings-field-sub">
                                <div className="settings-field">
                                    <h4 className={`settings-field-label`}>{wp.i18n.__("Darken Level", 'dracula-dark-mode')}</h4>
                                    <div className="settings-field-content">
                                        <RangeControl
                                            allowReset={true}
                                            resetFallbackValue={80}
                                            step={5}
                                            isShiftStepEnabled
                                            value={parseInt(darkenBackgroundImagesLevel)}
                                            onChange={darkenBackgroundImagesLevel => {
                                                setData({...data, darkenBackgroundImagesLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

                                        <p className="description">{wp.i18n.__("Set the darken level of the background images on dark mode", 'dracula-dark-mode')}</p>
                                    </div>
                                </div>
                            </div>
                        }

                    </div>

                    {/*Low Brightness*/}
                    <div className="settings-field field-low-brightness-images">
                        <h4 className={`settings-field-label`}>{wp.i18n.__('Low Brightness Images', 'dracula-dark-mode')}</h4>
                        <div className="settings-field-content">

                            <FormToggle
                                checked={lowBrightnessImages}
                                onChange={() => setData({...data, lowBrightnessImages: !lowBrightnessImages})}
                            />

                            <p className={'description'}>{wp.i18n.__("Enable low image brightness on dark mode", 'dracula-dark-mode')}</p>
                        </div>

                        {!!lowBrightnessImages &&
                            <div className="settings-field-sub">
                                <div className="settings-field">
                                    <h4 className={`settings-field-label`}>{wp.i18n.__("Brightness", 'dracula-dark-mode')}</h4>
                                    <div className="settings-field-content">
                                        <RangeControl
                                            allowReset={true}
                                            resetFallbackValue={80}
                                            step={5}
                                            isShiftStepEnabled
                                            value={parseInt(lowBrightnessLevel)}
                                            onChange={lowBrightnessLevel => {
                                                setData({...data, lowBrightnessLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

                                        <p className="description">{wp.i18n.__("Set the brightness level of the images on dark mode", 'dracula-dark-mode')}</p>
                                    </div>
                                </div>
                            </div>
                        }
                    </div>

                    {/* Grayscale Images */}
                    <div className="settings-field field-grayscale-images">
                        <h4 className={`settings-field-label`}>{wp.i18n.__('Grayscale Images', 'dracula-dark-mode')}</h4>
                        <div className="settings-field-content">

                            <FormToggle
                                checked={grayscaleImages}
                                onChange={() => setData({...data, grayscaleImages: !grayscaleImages})}
                            />

                            <p className={'description'}>{wp.i18n.__("Enable grayscale image on dark mode", 'dracula-dark-mode')}</p>
                        </div>

                        {!!grayscaleImages &&
                            <div className="settings-field-sub">
                                <div className="settings-field">
                                    <h4 className={`settings-field-label`}>{wp.i18n.__("Grayscale Level", 'dracula-dark-mode')}</h4>
                                    <div className="settings-field-content">
                                        <RangeControl
                                            allowReset={true}
                                            resetFallbackValue={80}
                                            step={5}
                                            isShiftStepEnabled
                                            value={parseInt(grayscaleImagesLevel)}
                                            onChange={grayscaleImagesLevel => {
                                                setData({...data, grayscaleImagesLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

                                        <p className="description">{wp.i18n.__("Set the grayscale level of the images on dark mode", 'dracula-dark-mode')}</p>
                                    </div>
                                </div>
                            </div>
                        }
                    </div>

                    {/* Invert Images */}
                    <div className="settings-field field-invert-images">
                        <h4 className={`settings-field-label`}>{wp.i18n.__('Invert Images', 'dracula-dark-mode')}</h4>
                        <div className="settings-field-content">

                            <FormToggle
                                checked={invertImages}
                                onChange={() => setData({...data, invertImages: !invertImages})}
                            />

                            <p className={'description'}>{wp.i18n.__("Enable invert colors of images on dark mode", 'dracula-dark-mode')}</p>
                        </div>

                        {!!invertImages &&
                            <div className="settings-field-sub">
                                <div className="settings-field">
                                    <h4 className={`settings-field-label`}>{wp.i18n.__("Invert Level", 'dracula-dark-mode')}</h4>
                                    <div className="settings-field-content">
                                        <RangeControl
                                            allowReset={true}
                                            resetFallbackValue={80}
                                            step={5}
                                            isShiftStepEnabled
                                            value={parseInt(invertImagesLevel)}
                                            onChange={invertImagesLevel => {
                                                setData({...data, invertImagesLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

                                        <p className="description">{wp.i18n.__(`Set the invert level of the images on dark mode`, 'dracula-dark-mode')}</p>
                                    </div>
                                </div>
                            </div>
                        }

                    </div>
                </>
            }
        </div>
    )
}