import AirDatepicker from 'air-datepicker';
import 'air-datepicker/air-datepicker.css';
import datePickerSv from 'air-datepicker/locale/sv.js';
import datePickerEn from 'air-datepicker/locale/en.js';
import Swal from 'sweetalert2';

import { EditorView, basicSetup } from "codemirror";
import { EditorState } from "@codemirror/state";
// Languages
import { html } from "@codemirror/lang-html";
import { javascript } from "@codemirror/lang-javascript";
import { css } from "@codemirror/lang-css";

// Theme (One Dark or use another)
import { oneDark } from "@codemirror/theme-one-dark";

// Highlighting style (optional but recommended)
import { defaultHighlightStyle } from "@codemirror/highlight";


let scheduleStartEl = document.getElementById('webien_schedule_start');
if(scheduleStartEl) {
    new AirDatepicker('#webien_schedule_start', {
        timepicker: true,
        timeFormat: 'HH:mm',
        minMinutes: 0,
        maxMinutes: 0,
        locale: datePickerSv,
        buttons: ['clear']
    });
}

let scheduleStopEl = document.getElementById('webien_schedule_stop');
if(scheduleStopEl) {
    new AirDatepicker('#webien_schedule_stop', {
        timepicker: true,
        timeFormat: 'HH:mm',
        minMinutes: 0,
        maxMinutes: 0,
        locale: datePickerSv,
        buttons: ['clear']
    });
}

let scheduleToggleBtn = document.getElementById('toggle-webien-schedule');
if(scheduleToggleBtn){
    scheduleToggleBtn.onclick = function(){
        let container = document.getElementById('webien_schedule_container');
        if(container){
            container.classList.toggle('open');
        }
    };
}



// Ajax call for removing wp_option field from settings page
jQuery('#webien_remove_option').on('click', function(){
    let optionName = jQuery('#webien_option_name').val();
    if(optionName){
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'webien_remove_option',
                option_name: optionName
            },
            success: function(response){
                if(response.success){
                    alert(optionName + ' raderades från wp_options tabellen.');
                }
                else {
                    alert(optionName + ' hittades inte i wp_options tabellen.');
                }
            },
            error: function(response){
                alert('Error: ' + response);
            }
        });
    }

});





// Ajax call for update/database operations
const dbLoader = jQuery('.acf-field-webien-update-tools-webien-update-buttons-message .loading');
jQuery('#webien_update_create_db_dump').on('click', function(){

    dbLoader.show();

    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'webien_update_create_db_dump',
        },
        success: function(response){
            if(response.success){
                    Swal.fire({
                        icon: "success",
                        title: "Klart!",
                        confirmButtonText: "Ok",
                        text: "Databasdump skapades. Sidan kommer laddas om för att visa din dump nedan.",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            location.reload();
                            dbLoader.hide();

                        }
                    });
            } else {
                Swal.fire({
                    icon: "error",
                    title: "Oops...",
                    text: "Något gick fel..",
                    confirmButtonText: "Ok",
                });
                dbLoader.hide();

            }
        },
        error: function(response){
            console.log('Error: ' + response);
            Swal.fire({
                icon: "error",
                title: "Oops...",
                text: "Något gick fel.. Databasen kunde inte skapas.",
                confirmButtonText: "Ok",
            });
            dbLoader.hide();
        }
    });
});
jQuery('#webien_update_back_db_dump').on('click', function(){


    Swal.fire({
        icon: "warning",
        title: "Är du säker?",
        confirmButtonText: "Kör på",
        showCancelButton: true,
        cancelButtonText: "Avbryt",
        text: "Dubbelkolla tidpunkt för dumpen så att den inte är gammal. Databasen kommer att återställas till den tidpunkten.",
    }).then((result) => {
        if (result.isConfirmed) {
            dbLoader.show();

            jQuery.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'webien_update_back_db_dump',
                },
                success: function(response){
                    if(response.success){
                        Swal.fire({
                            icon: "success",
                            title: "Klart!",
                            confirmButtonText: "Ok",
                            text: "Databasdump återställdes.",
                        }).then((result) => {
                            if (result.isConfirmed) {
                                dbLoader.hide();
                            }
                        });
                    }  else {
                        Swal.fire({
                            icon: "error",
                            title: "Oops...",
                            text: "Något gick fel.. Databasen kunde inte återställas.",
                            confirmButtonText: "Ok",
                        });
                        dbLoader.hide();
                    }
                },
                error: function(response){
                    console.log(response);
                    Swal.fire({
                        icon: "error",
                        title: "Oops...",
                        text: "Något gick fel.. Databasen kunde inte återställas.",
                        confirmButtonText: "Ok",
                    });
                    dbLoader.hide();
                }
            });

        }
    });




});
jQuery('#webien_update_remove_db_dump').on('click', function(){
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'webien_update_remove_db_dump',
        },
        success: function(response){
            if(response.success){
                Swal.fire({
                    icon: "success",
                    title: "Klart!",
                    confirmButtonText: "Ok",
                    text: "Databasdump borttagen.",
                }).then((result) => {
                    if (result.isConfirmed) {
                        dbLoader.hide();
                    }
                });
            } else {
                Swal.fire({
                    icon: "error",
                    title: "Oops...",
                    text: "Något gick fel.. Databasen kunde inte tas bort.",
                    confirmButtonText: "Ok",
                });
                dbLoader.hide();
            }
        },
        error: function(response){
            console.log('Error: ' + response);
            Swal.fire({
                icon: "error",
                title: "Oops...",
                text: "Något gick fel.. Databasen kunde inte tas bort.",
                confirmButtonText: "Ok",
            });
            dbLoader.hide();
        }
    });
});



// --------------------------------------- //
// Admin styles & scripts


document.addEventListener("DOMContentLoaded", () => {

    const parent = document.getElementById("webien_admin_custom_html_editor");
    const textArea = document.getElementById("acf-field_webien_admin_scripts_webien_admin_custom_html");

    if(!parent || !textArea) return;

    // Create 10 blank lines
    //const startingValue = "\n".repeat(10);
    const startingValue = textArea.value;

    const state = EditorState.create({
        doc: startingValue,
        extensions: [
            basicSetup,
            // Theme
            oneDark,                // or use a light theme below

            // Syntax highlighting enhancements
            //defaultHighlightStyle,

            // HTML automatically handles inline JS/CSS,
            // but you can also add standalone modes:
            html(),
            javascript(),
            css(),
            // SYNC BACK TO TEXTAREA
            EditorView.updateListener.of((update) => {
                if (update.docChanged) {
                    textArea.value = update.state.doc.toString();
                }
            })
            //html(),   // syntax highlighting for HTML
        ],
    });

    const view = new EditorView({
        state,
        parent,  // attaches to the <div>
    });




});