const {SelectControl, FormToggle} = wp.components;
const {useState} = React;

export default function Tools({data, setData}) {

    const {exportData = 'all', autoSave} = data;

    const [isLoading, setIsLoading] = useState(false);

    const getExportData = () => {
        setIsLoading('export');

        wp.ajax.post('rp_get_export_data', {
            type: exportData,
            nonce: radioPlayer.nonce,
        })
            .done(response => {
                const json = JSON.stringify(response);
                const blob = new Blob([json], {type: 'application/json'});
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');

                link.href = url;
                link.download = `radio-player-export-${exportData.replace('_', '-')}-${new Date().toISOString().slice(0, 10)}.json`;
                link.click();

                URL.revokeObjectURL(url);
            })
            .fail((error) => console.log(error))
            .always(() => setIsLoading(false));
    }

    const importData = () => {

        //create file input
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'application/json';
        input.onchange = () => {
            //get file
            const file = input.files[0];
            //read file
            const reader = new FileReader();
            reader.readAsText(file);
            reader.onload = () => {
                setIsLoading('import');

                //Get data
                const json = JSON.parse(reader.result);

                wp.ajax.post('rp_import_data', {
                    data: json,
                    nonce: radioPlayer.nonce,
                }).done(() => {
                    Swal.fire({
                        title: wp.i18n.__('Imported!', 'radio-player'),
                        text: wp.i18n.__('Data imported successfully.', 'radio-player'),
                        icon: 'success',
                        showConfirmButton: false,
                        timer: 2500,
                        timerProgressBar: true,
                        toast: true,
                        customClass: {
                            container: 'radio-player-swal radio-player-swal-toast',
                        }
                    });

                    if (json.settings) {
                        setData(json.settings);
                    }

                })
                    .fail((error) => console.log(error))
                    .always(() => setIsLoading(false));
            }
        }

        //click file input
        input.click();
    }

    return (
        <div className="tab-content">

            <div className="settings-header">
                <img src={`${radioPlayer.plugin_url}/assets/images/settings/tools.svg`} />


                <span>{wp.i18n.__('Tools', 'radio-player')}</span>
            </div>

            {/* Enable Auto Save */}
            <div className={`setting-field field-show-toggle`}>
                <h4 className={`setting-field-label`}>{wp.i18n.__('Enable Auto-save Settings', 'dracula-dark-mode')}</h4>
                <div
                    className={`setting-field-content`}>
                    <FormToggle
                        checked={autoSave}
                        onChange={() => setData({...data, autoSave: !autoSave})}
                    />

                    <p className="description">{wp.i18n.__('Enable automatic saving when you change a setting', 'dracula-dark-mode')}</p>
                </div>
            </div>

            {/* Export Data */}
            <div className="setting-field">
                <label className={`setting-field-label`}>{wp.i18n.__("Export Data", "radio-player")}</label>
                <div className="setting-field-content">

                    <SelectControl
                        value={exportData}
                        options={[
                            {label: wp.i18n.__("Players", "radio-player"), value: 'players'},
                            {label: wp.i18n.__("Settings", "radio-player"), value: 'settings'},
                            {label: wp.i18n.__("Export All ( Players, Settings )", "radio-player"), value: 'all'},
                        ]}
                        onChange={exportData => {
                            setData({...data, exportData})
                        }}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}

                    />
                    <p className="description">{wp.i18n.__("Select the data you want to export.", "radio-player")}</p>

                    <button type={`button`} className={`radio-player-btn btn-primary`} onClick={getExportData}>

                        {'export' === isLoading ? <div className="radio-player-spinner"></div> :
                            <i className={`dashicons dashicons-download`}></i>}

                        <span>{wp.i18n.__("Export", "radio-player")}</span>
                    </button>

                    <p className="description">{wp.i18n.__("Export the selected data to a JSON file.", "radio-player")}</p>
                </div>
            </div>

            {/* Import Settings */}
            <div className="setting-field">
                <label className={`setting-field-label`}>{wp.i18n.__("Import Data", "radio-player")}</label>
                <div className="setting-field-content">
                    <button type={`button`} className={`radio-player-btn btn-info`} onClick={importData}>
                        {'import' === isLoading ? <div className="radio-player-spinner"></div> :
                            <i className={`dashicons dashicons-upload`}></i>}
                        <span>Import</span>
                    </button>

                    <p className="description">{wp.i18n.__("Select the exported JSON file you would like to import. Please note that the import will replace the current data", "radio-player")}</p>
                </div>
            </div>

            {/*  Reset Settings */}
            <div className="setting-field">
                <label className={`setting-field-label`}>{wp.i18n.__("Reset Settings", "radio-player")}</label>

                <div className="setting-field-content">
                    <button type={`button`} className={`radio-player-btn btn-danger`} onClick={() => {
                        Swal.fire({
                            title: wp.i18n.__('Are you sure?', 'radio-player'),
                            text: wp.i18n.__('We recommend you to export your current settings before resetting them.', 'radio-player'),
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonText: wp.i18n.__('Reset', 'radio-player'),
                            reverseButtons: true,
                            showLoaderOnConfirm: true,
                            customClass: {container: 'radio-player-swal'},
                        }).then((result) => {
                            if (result.value) {
                                setData({});
                            }
                        });
                    }}>
                        <i className={`dashicons dashicons-update`}></i>
                        <span>{wp.i18n.__("Reset", "radio-player")}</span>
                    </button>

                    <p className="description">{wp.i18n.__("Reset all settings to default.", "radio-player")}</p>
                </div>
            </div>


        </div>
    )
}