import SettingsContext from "../../contexts/SettingsContext";
import Header from "./Header";
import LiveEditButton from "./LiveEditButton";
import SelectVideo from "../LiveEdit/SelectVideo";
import {videoReplacements} from "../../includes/functions";
import {showProModal} from "../ProModal";
import {Tooltip} from "react-tooltip";
import VideoPreview from "./Preview/VideoPreview";

const {FormToggle, RangeControl} = wp.components;

const {useRef, useContext, useState} = React;

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

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

    const {
        videos = [{}],
        lowBrightnessVideos = false,
        videoBrightnessLevel = 80,
        grayscaleVideos = false,
        grayscaleVideosLevel = 80,
    } = data;

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

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

    const frameRef = useRef();

    const updateVideo = (index, type, video) => {
        setCurrentItem(index);

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

    const selectVideo = (index, type) => {

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

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

            }).open();
            return;
        }

        frameRef.current = wp.media({
            title: 'Select Video',
            button: {text: 'Use this video'},
            library: {type: 'video'},
            multiple: false
        });

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

    const removeGroup = (index) => {
        const newVideos = [...videos.slice(0, index), ...videos.slice(index + 1)];
        setData({...data, videos: newVideos});

        if (isLiveEdit) {
            videoReplacements(newVideos, true);
        }
    }


    return (
        <div className="dracula-settings-content field-video-settings">

            <Header title={wp.i18n.__('Video Settings', 'dracula-dark-mode')}/>

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

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

            {
                'video-replacement' === innerTab &&
                <>
                    {/* Video Replacement */}
                    <div className={`settings-field field-video-settings ${!isPro ? 'pro-feature' : ''}`}>

                        <div className="settings-field-content">
                            <div className="image-replacements">
                                <h3>
                                    {wp.i18n.__('Video Replacement', 'dracula-dark-mode')}
                                    {!isPro && <span className="dracula-pro-icon"><i className={`dracula-icon icon-pro`}/></span>}
                                </h3>

                                {!isLiveEdit &&
                                    <>
                                        <p>
                                            {wp.i18n.__('Replace specific videos when dark mode is enabled. You can replace any self-hosted, youtube, vimeo and dailymotion videos.', '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 Videos', 'dracula-dark-mode')}</span>
                                                    <p>{wp.i18n.__('Enter the video links or select the videos 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 Videos', 'dracula-dark-mode')}</span>
                                                    <p>{wp.i18n.__('Enter the video links or select the videos that will be displayed in the dark mode replacing the light videos.', '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>
                                    </>
                                }

                                {videos.map((image, index) => {
                                    const lightImage = image.light;
                                    const darkImage = image.dark;

                                    return (
                                        <div
                                            data-tooltip-content={!isPro ? wp.i18n.__('PRO Feature', 'dracula-dark-mode') : ''}
                                            className="image-replacements-group"
                                            onClick={() => {
                                                if (!isPro) {
                                                    showProModal();
                                                }
                                            }}
                                            key={index}
                                        >
                                            <div className="group-item">
                                                <div className="input-group">
                                                    <VideoPreview url={lightImage}/>

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

                                                    {!!isLiveEdit && 'classic' !== isEditor &&
                                                        <SelectVideo data={data} setData={setData} index={index}
                                                                     setCurrentItem={setCurrentItem}/>
                                                    }
                                                    <button type="button"
                                                            className="dracula-btn btn-primary input-group-append"
                                                            onClick={() => selectVideo(index, 'light')}>
                                                        <span className="dracula-btn-icon icon-add-video"></span>
                                                        <span>{wp.i18n.__('Browse', 'dracula-dark-mode')}</span>
                                                    </button>
                                                </div>
                                            </div>

                                            {/* Dark Mode Videos */}
                                            <div className="group-item">
                                                <div className="input-group">
                                                    <VideoPreview url={darkImage} isDark="true"/>

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

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

                                            {(index === currentItem && isLiveEdit) ?
                                                <button type={`button`} className="dracula-btn btn-primary"
                                                        onClick={() => {
                                                            setCurrentItem(null);
                                                            if (draculaDarkMode.isEnabled()) {
                                                                videoReplacements(videos);
                                                            }
                                                        }}>
                                                    <span>{wp.i18n.__('Update', 'dracula-dark-mode')} </span>
                                                </button>
                                                :
                                                <button type={`button`} className="dracula-btn btn-danger"
                                                        onClick={() => 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`} effect="solid" place="left"
                                                    backgroundColor="#ff9966" className={'dracula-tooltip'}/>}

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

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

                            </div>

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

                        </div>


                    </div>
                </>
            }

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

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

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

                        {!!lowBrightnessVideos &&
                            <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(videoBrightnessLevel)}
                                            onChange={videoBrightnessLevel => {
                                                setData({...data, videoBrightnessLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

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

                    </div>

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

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

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

                        {!!grayscaleVideos &&
                            <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(grayscaleVideosLevel)}
                                            onChange={grayscaleVideosLevel => {
                                                setData({...data, grayscaleVideosLevel});
                                            }}
                                            min={0}
                                            max={100}
                                            className={`dracula-range-control`}
                                        />

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

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