import {ToggleBuilderProvider} from "../contexts/ToggleBuilderContext";
import EmptyPlaceholder from "./ToggleBuilder/EmptyPlaceholder";
import List from "./ToggleBuilder/List";
import FormBuilder from "./ToggleBuilder/FormBuilder";
import Preview from "./ToggleBuilder/Preview";
import {base64Encode, removeIdParam, setIdParam, useMounted} from "../includes/functions";
import ProModal from "./ProModal";


const {useState, useEffect} = React;

const {isPro, customToggles = []} = dracula;

export default function ToggleBuilder() {

    const initData = {
        title: wp.i18n.__('Button Name', 'dragula-dark-mode'),
        status: true,
        layout: 1,
        lightIcon: 1,
        darkIcon: 11,
        backgroundColorType: 'solid',
        lightBackgroundColor: '#EEE',
        darkBackgroundColor: '#00288F',
        lightTextColor: '#4B5D8A',
        darkTextColor: '#FFFFFF',
        width: 50,
        padding: 10,
        borderRadius: 10,
        lightBorderColor: '#4B5D8A',
        darkBorderColor: '#FFFFFF',
        borderWidth: 0,
        tooltipText: wp.i18n.__('Toggle Dark Mode', 'dragula-dark-mode'),
    }

    const [data, setData] = useState(initData);

    const {id, title} = data;

    const [state, setState] = useState('light');
    const [isUpdating, setIsUpdating] = useState(false);
    const [edit, setEdit] = useState(isPro ? false : -1);
    const [filteredToggles, setFilteredToggles] = useState([]);
    const [toggles, setToggles] = useState(customToggles);
    const [perPage, setPerPage] = useState(localStorage.getItem('dracula_shortcode_list_per_page') || 10);
    const [sortBy, setSortBy] = useState(localStorage.getItem('dracula_shortcode_list_sort_by') || 'id');
    const [sortOrder, setSortOrder] = useState(localStorage.getItem('dracula_shortcode_list_sort_order') || 'desc');

    const [page, setPage] = useState(1);

    const updateToggle = (toggleData) => {
        setIsUpdating(true);

        return wp.ajax
            .post('dracula_update_toggle', {
                data: base64Encode(JSON.stringify(toggleData)),
                nonce: dracula.nonce,
            })
            .done((response) => {
                setData({...toggleData, id: parseInt(response.id)});

                if (!!toggleData.id) {
                    const index = toggles.findIndex(item => item.id == response.id);

                    let items = [...toggles];
                    items[index] = {...items[index], ...response};
                    setToggles(items);
                } else {
                    setToggles([response, ...toggles]);
                }


                Swal.fire({
                    title: wp.i18n.__("Updated!", "dracula-dark-mode"),
                    text: wp.i18n.__("Toggle has been updated.", "dracula-dark-mode"),
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false,
                    toast: true,
                    position: 'top-end',
                    customClass: {
                        container: 'dracula-swal',
                    },
                });
            })
            .fail(error => {
                console.log(error);

                Swal.fire({
                    title: wp.i18n.__("Error!", "dracula-dark-mode"),
                    text: wp.i18n.__("Something went wrong while updating the toggle.", "dracula-dark-mode"),
                    icon: 'error',
                    timer: 1500,
                    showConfirmButton: false,
                    toast: true,
                    position: 'top-end',
                    customClass: {
                        container: 'dracula-swal',
                    },
                });
            })
            .always(() => {
                setEdit(false);
                setIsUpdating(false);
            });
    }

    const deleteToggle = (id, isEdit = false) => {

        return wp.ajax
            .post('dracula_delete_toggle', {id, nonce: dracula.nonce,})
            .done(() => {
                setToggles(toggles => toggles.filter(item => item.id != id));

                if (isEdit) {
                    removeIdParam();
                    setEdit(false);
                }

                Swal.fire({
                    title: wp.i18n.__("Deleted!", "dracula-dark-mode"),
                    text: wp.i18n.__("Toggle has been deleted.", "dracula-dark-mode"),
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false,
                    toast: true,
                    position: 'top-end',
                    customClass: {
                        container: 'dracula-swal',
                    },
                });
            }).fail(error => {
                console.log(error);

                Swal.fire({
                    title: wp.i18n.__("Error!", "dracula-dark-mode"),
                    text: wp.i18n.__("Something went wrong while deleting the toggle.", "dracula-dark-mode"),
                    icon: 'error',
                    timer: 1500,
                    showConfirmButton: false,
                    toast: true,
                    position: 'top-end',
                    customClass: {
                        container: 'dracula-swal',
                    },
                });
            });
    }

    const duplicateToggle = ids => {
        setIsUpdating(true);

        return wp.ajax.post('dracula_duplicate_toggle', {
            ids,
            nonce: dracula.nonce,
        }).done((data) => {
            console.log(data);

            setToggles([...data, ...toggles]);

            Swal.fire({
                title: wp.i18n.__("Duplicated!", "dracula-dark-mode"),
                text: wp.i18n.__("Toggle has been duplicated.", "dracula-dark-mode"),
                icon: 'success',
                timer: 2000,
                showConfirmButton: false,
                toast: true,
                position: 'top-end',
                customClass: {
                    container: 'dracula-swal',
                },
            });
        }).fail(error => {
            console.log(error);

            Swal.fire({
                title: wp.i18n.__("Error!", "dracula-dark-mode"),
                text: wp.i18n.__("Something went wrong.", "dracula-dark-mode"),
                icon: 'error',
                timer: 2000,
                showConfirmButton: false,
                toast: true,
                position: 'top-end',
                customClass: {
                    container: 'dracula-swal',
                },
            });

        }).always(() => {
            setIsUpdating(false);
        });
    }

    const isMounted = useMounted();

    useEffect(() => {
        if (!isPro || '-1' != edit) return;
        document.getElementById('toggle-title').focus();
    }, [edit]);

    // Update data on edit
    useEffect(() => {
        if (!isPro || edit < 1) {
            setData(initData);
            return;
        }

        setIdParam(edit);

        const data = {...toggles.find(item => item.id == edit)['config'], id: parseInt(edit)};
        setData(data);
    }, [edit]);

    // Handle Sorting
    useEffect(() => {

        let data = [...toggles];

        if (sortBy) {
            data.sort((a, b) => {
                const aVal = a[sortBy];
                const bVal = b[sortBy];

                const isNumeric = sortBy === 'id';

                if (isNumeric) {
                    return sortOrder === 'asc'
                        ? Number(aVal) - Number(bVal)
                        : Number(bVal) - Number(aVal);
                }

                return sortOrder === 'asc'
                    ? String(aVal).localeCompare(String(bVal))
                    : String(bVal).localeCompare(String(aVal));
            });
        }

        setFilteredToggles(data);

    }, [toggles, sortBy, sortOrder]);

    return (
        <div className="dracula-toggle-builder">

            <div className="dracula-toggle-builder-header">
                <div className="header-title">
                    <img src={dracula.pluginUrl + '/assets/images/toggle-builder/builder-icon.svg'}/>

                    {!edit ?
                        <span>{wp.i18n.__("Toggle Builder", "dracula-dark-mode")}</span>
                        :
                        <>
                            <label
                                htmlFor={"toggle-title"}>{id > 0 ? wp.i18n.__("Edit Toggle", "dracula-dark-mode") : wp.i18n.__("Add New Toggle", "dracula-dark-mode")}</label>
                            <input type="text"
                                   onChange={e => setData(data => ({...data, title: e.target.value}))}
                                   value={title}
                                   className={"toggle-title"}
                                   id={"toggle-title"}
                            />
                        </>
                    }

                </div>

                <div className="header-actions">
                    {!!edit ?
                        <>
                            <button type={`button`} className={`dracula-btn btn-outline-primary back-btn`}
                                    onClick={() => {
                                        removeIdParam();

                                        setEdit(false);
                                    }}>
                                <i className="dashicons dashicons-arrow-left-alt2"></i>
                                <span>{wp.i18n.__("Back", "dracula-dark-mode")}</span>
                            </button>

                            <button type={`button`} className={`dracula-btn btn-danger`}
                                    onClick={() => deleteToggle(id, true)}>
                                <i className={`dashicons dashicons-trash`}></i>
                                <span>{wp.i18n.__("Delete", "dracula-dark-mode")}</span>
                            </button>

                            <button className="dracula-btn btn-primary" onClick={() => updateToggle(data)}>
                                {isUpdating ? <div className="dracula-spinner"></div> : <i className={`dashicons dashicons-saved`}></i>}
                                {wp.i18n.__('Save', "dracula-dark-mode")}
                            </button>

                        </>
                        :
                        <button type={`button`} className={`dracula-btn btn-primary add-new-btn`}
                                onClick={() => setEdit(-1)}>
                            <i className="dashicons dashicons-plus"></i>
                            <span>{wp.i18n.__("Add New", "dracula-dark-mode")}</span>
                        </button>
                    }
                </div>
            </div>


            {!!edit &&
                <ToggleBuilderProvider value={{data, setData, state, setState, isUpdating, updateToggle, deleteToggle}}>
                    <div className={`dracula-toggle-builder-form`}>

                        <FormBuilder/>

                        <Preview/>

                    </div>
                </ToggleBuilderProvider>
            }

            {!edit && !toggles.length && <EmptyPlaceholder setEdit={setEdit}/>}
            {!edit && !!toggles.length &&
                <List
                    toggles={toggles}
                    filteredToggles={filteredToggles}
                    deleteToggle={deleteToggle}
                    duplicateToggle={duplicateToggle}
                    setEdit={setEdit}
                    perPage={perPage}
                    setPerPage={setPerPage}
                    sortBy={sortBy}
                    setSortBy={setSortBy}
                    sortOrder={sortOrder}
                    setSortOrder={setSortOrder}
                    page={page}
                    setPage={setPage}
                />
            }


            {!isPro &&
                <ProModal
                    isDismissable={false}
                    text={wp.i18n.__('Upgrade to PRO to create customized dark mode toggle button.', 'dracula-dark-mode')}
                    watchVideo={{
                        id: 'lpx0ndyYoZ8',
                        title: wp.i18n.__('Custom Dark Mode Toggle Button', 'dracula-dark-mode')
                    }}
                />
            }

        </div>
    )
}