import { Ajax, Toast, Vn, isTrue, FilePondHandler, mockServer, Log } from "./helper";

const Setup = {
    state: {
        setupStarted: 1,
        currentStep: 1,
        stepScreen: 1,
        steps: [
            wp.i18n.__("Set Credentials", "stock-sync-with-google-sheet-for-woocommerce"),
            wp.i18n.__("Set URL", "stock-sync-with-google-sheet-for-woocommerce"),
            wp.i18n.__("Set ID", "stock-sync-with-google-sheet-for-woocommerce"),
            wp.i18n.__("Configure Apps Script", "stock-sync-with-google-sheet-for-woocommerce"),
            wp.i18n.__("Done", "stock-sync-with-google-sheet-for-woocommerce"),
        ],
    },

    ssgsw_script: ssgsw_script,
    option: {},
    show_notice_popup_setup : false,
    get credentials() {
        return this.option.credentials || {};
    },

    get limit() {
        return this.ssgsw_script.limit;
    },

    get is_woocommerce_installed() {
        return isTrue(this.ssgsw_script.is_woocommerce_installed);
    },

    get is_woocommerce_activated() {
        return isTrue(this.ssgsw_script.is_woocommerce_activated);
    },

    get isPro() {
        return isTrue(this.ssgsw_script.is_license_valid);
    },

    /**
     * Tabbing
     */
    get step() {
        return this.ssgsw_script.options.setup_step || 1;
    },

    isStep(step) {
        return this.state.currentStep === step;
    },
    get isFirstScreen() {
        return this.state.stepScreen === 1;
    },

    setStep(step) {
        this.state.currentStep = step;
        window.location.hash = `#step-${step}`;
    },

    showPrevButton() {
        return (
        (this.state.currentStep > 1 || !this.isFirstScreen) &&
        this.state.currentStep !== 5
    );
    },

    showNextButton() {
        if (this.state.currentStep === 5) {
            return false;
        }

        switch (this.state.currentStep) {
        /**
         * Middleware for step 1
         */
        case 1:
        default:
            if (this.isFirstScreen) {
                return this.option.credentials;
            }

            return this.state.enabled_google_sheet_api || false; 

        /**
         * Middleware for step 2
         */
        case 2:
            let valid = false;

            // check if spreadsheet_url is valid url
            if (this.option.spreadsheet_url) {
                valid = this.option.spreadsheet_url.match(
                    /^https:\/\/docs.google.com\/spreadsheets\/d\/[a-zA-Z0-9-_]+\/edit/
                );
            }

            if (!valid) { return false;
            }

            return this.option.sheet_tab.trim().length > 0;
 

        /**
         * Middleware for step 3
         */
        case 3:
            return this.state.given_editor_access || false; 
        /**
         * Middleware for step 4
         */
        case 4:
            if (this.isFirstScreen) {
                return this.state.pasted_apps_script || false;
            }

            return this.state.triggered_apps_script || false; 
        }

        return false;
    },

    prevScreen() {
        if (this.isFirstScreen) {
            this.state.currentStep--;
        }

        this.state.stepScreen = 1;

        this.state.doingPrev = true;
        this.state.doingNext = false;
        this.setStep(this.state.currentStep);
    },

    nextScreen() {
        if (this.isFirstScreen && ![2, 3].includes(this.state.currentStep)) {
            this.state.stepScreen = 2;
        } else {
            this.state.stepScreen = 1;
            this.state.currentStep++;
        }

        this.state.doingNext = true;
        this.state.doingPrev = false;
    },

    clickPreviousButton() {
        this.prevScreen();
    },

    async clickNextButton() {
        let response = null;

        switch (this.state.currentStep) {
        // Set credentials
        case 1:
            if (this.isFirstScreen) {
                let credentials = this.option.credentials;
                response = await Ajax.post(
                    "ssgsw_update_options", {
                        options: {
                            credentials: JSON.stringify(credentials),
                            credential_file: this.option.credential_file,
                            setup_step: 2,
                        },
                    }
                );
                Log(response);
                if (response.success) {
                      this.nextScreen();
                } else {
                    Toast.fire(
                        {
                            icon: "error",
                            title: wp.i18n.sprintf(wp.i18n.__("FlexStock: %s", "stock-sync-with-google-sheet-for-woocommerce"), response.message || wp.i18n.__("No product found. Try again", "stock-sync-with-google-sheet-for-woocommerce")),
                        }
                    );
                }
            } else {
                response = await Ajax.post(
                    "ssgsw_update_options", {
                        options: { setup_step: 2 },
                    }
                );
                this.nextScreen();
            }
            break;

        // Set spreadsheet url
        case 2:
            response = await Ajax.post(
                "ssgsw_update_options", {
                    options: {
                        spreadsheet_url: this.option.spreadsheet_url,
                        sheet_tab: this.option.sheet_tab,
                        setup_step: 3,
                    },
                }
            );

            if (response.success) {
                this.nextScreen();
            } else {
                Toast.fire(
                    {
                        icon: "error",
                        title: wp.i18n.sprintf(wp.i18n.__("FlexStock: %s", "stock-sync-with-google-sheet-for-woocommerce"), response.message || wp.i18n.__("Something went wrong", "stock-sync-with-google-sheet-for-woocommerce")),
                    }
                );
            }

            break;

        // Set editor access
        case 3:
            this.state.loadingNext = true;
            response = await Ajax.post("ssgsw_init_sheet");
            this.state.loadingNext = false;

            Log("Sheet initialized", response);

            if (response.success) {
                Toast.success(wp.i18n.__("FlexStock: Google Sheet is connected", "stock-sync-with-google-sheet-for-woocommerce"));

                response = await Ajax.post(
                    "ssgsw_update_options", {
                        options: {
                            setup_step: 4,
                        },
                    }
                );

                this.nextScreen();
            } else {
                Toast.fire(
                    {
                        timeout: false,
                        icon: "error",
                        title: wp.i18n.__("FlexStock: Ops! Something went wrong", "stock-sync-with-google-sheet-for-woocommerce"),
                        content: wp.i18n.sprintf(wp.i18n.__("FlexStock: %s", "stock-sync-with-google-sheet-for-woocommerce"), response.message || wp.i18n.__("Something went wrong", "stock-sync-with-google-sheet-for-woocommerce")),
                        position: "center",
                    }
                );
            }

            break;

        // Set apps script
        case 4:
            if (!this.isFirstScreen) {
                response = await Ajax.post(
                    "ssgsw_update_options", {
                        options: {
                            setup_step: 5,
                            apps_script__notice: 1,
                        },
                    }
                );

                this.nextScreen();
            } else {
                this.nextScreen();
            }

            break;

        default:
            response = await Ajax.post(
                "ssgsw_update_options", {
                    options: {
                        setup_step: this.currentStep + 1,
                    },
                }
            );

            this.nextScreen();
            break;
        }
    },

    init() {
        this.ssgsw_script = ssgsw_script || {};
        this.option = this.ssgsw_script.options || {};
        Log(this.ssgsw_script);

        if (this.option.setup_step) {
            this.state.setupStarted = true;
            this.state.currentStep = Number(this.option.setup_step);
        } else {
            this.state.setupStarted = false;
            this.state.currentStep = 1;
        }

        // let hash = window.location.hash;
        // if (hash) {
        //   let step = hash.replace("#step-", "");
        //   if (step) {
        //     this.state.currentStep = parseInt(step);
        //     this.state.stepScreen = 1;
        //     this.state.setupStarted = true;
        //   }
        // }

        /**
         * Init FilePond
         */

        this.handleFilePond();

        /**
         * YouTube players
         */
        this.playVideos();
    },

    async activateWooCommerce() {
        if (this.state.activatingWooCommerce) { return;
        }

        this.state.activatingWooCommerce = true;

        const response = await Ajax.post("ssgsw_activate_woocommerce");

        this.state.activatingWooCommerce = false;

        if (response.success) {
            this.state.activatingWooCommerce = false;
            this.ssgsw_script.is_woocommerce_activated = true;
            this.ssgsw_script.is_woocommerce_installed = true;
        } else {
            Toast.fire(
                {
                    icon: "error",
                    title: wp.i18n.sprintf(wp.i18n.__("FlexStock: %s", "stock-sync-with-google-sheet-for-woocommerce"), response.message || wp.i18n.__("Something went wrong", "stock-sync-with-google-sheet-for-woocommerce")),
                }
            );
        }
    },

    /**
     * Copy Service Account Credentials
     */
    copyServiceAccountEmail() {
        if ("client_email" in this.credentials && this.credentials.client_email) {
            const el = document.createElement("textarea");
            el.value = this.credentials.client_email;
            document.body.appendChild(el);
            el.select();
            document.execCommand("copy");
            document.body.removeChild(el);

            this.state.copied_client_email = true;

            Toast.success(wp.i18n.__("FlexStock: Copied to clipboard", "stock-sync-with-google-sheet-for-woocommerce"));

            setTimeout(
                () => {
                this.state.copied_client_email = false;
                }, 3000
            );
        }
    },

    /**
     * Copy Apps Scrips
     */
    copyAppsScript() {
        let script = this.ssgsw_script.apps_script;

        script = script.replace("{site_url}", this.ssgsw_script.site_url);
        script = script.replace("{token}", this.option.token);
        script = script.replace("{sheet_tab}", this.option.sheet_tab);
        script = script.replace("{token_id}", this.ssgsw_script.token_id);
        script = script.replace("{vendor_request}", this.ssgsw_script.vendor_request);

        script = script.replace(/\s+/g, " ");

        const el = document.createElement("textarea");
        el.value = script;
        document.body.appendChild(el);
        el.select();
        document.execCommand("copy");
        document.body.removeChild(el);

        this.state.copied_apps_script = true;

        Toast.success(wp.i18n.__("FlexStock: Copied to clipboard", "stock-sync-with-google-sheet-for-woocommerce"));

        setTimeout(
            () => {
            this.state.copied_apps_script = false;
            }, 3000
        );
    },

    // handleFilePond
    handleFilePond() {
        this.state.pond = FilePondHandler().create(
            document.querySelector('input[type="file"]'),
            {
                credits: false,
                server: mockServer,
                allowFilePoster: false,
                allowImageEditor: false,
                labelIdle: `<div class="ssgs-upload"><div>${wp.i18n.__('Drag and drop the <strong><i>credential.json</i></strong> file here', 'stock-sync-with-google-sheet-for-woocommerce')}</div> <span>${wp.i18n.__('OR', 'stock-sync-with-google-sheet-for-woocommerce')}</span> <div><span class="upload-button">${wp.i18n.__('Upload file', 'stock-sync-with-google-sheet-for-woocommerce')}</span></div> <div class="ssgs-uploaded-file-name" x-show="option.credential_file || false">
                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
                <path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" />
                </svg> <i x-html="option.credential_file"></i> ${wp.i18n.__('Uploaded', 'stock-sync-with-google-sheet-for-woocommerce')}
                </div></div>`,
                // restrict to files with the following extensions
                acceptedFileTypes: ["json"],
                maxFiles: 1,
                required: true,
                dropOnPage: true,
            }
        );

    this.state.pond.beforeDropFile = this.beforeDropFile;
    this.state.pond.beforeAddFile = this.beforeDropFile;

    /**
     * Handle file upload
     */
    this.state.pond.on(
        "processfile", (error, file) => {
            if (error) {
                return;
            }
            const reader = new FileReader();
            reader.onload = (e) => {
        const data = JSON.parse(e.target.result);
        Log(data);
        /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Validate credentials
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 */

                let isValid = true;
        const required_keys = [
                "client_email",
                "private_key",
                "type",
                "project_id",
                "client_id",
                ];
        required_keys.forEach(
                (key) => {
                    if (!data[key]) {
                        isValid = false;
                        }
                }
            );
            if (isValid) {
                Log("Uploading " + file.filename);
                this.option.credential_file = file.filename;
                this.option.credentials = data;
                this.state.pond.removeFiles();
                this.clickNextButton();
            } else {
        Toast.fire(
                {
                    position: 'center',
                    timeout: false,
                    icon: "error",
                    title: wp.i18n.__("FlexStock: Invalid credentials", "stock-sync-with-google-sheet-for-woocommerce"),
                        }
                );
        this.state.pond.removeFiles();
            }
            };
            reader.readAsText(file.file);
            // var nextBtn = document.getElementById( "nextBtn" );

            // nextBtn.setAttribute("onclick", "nextPrev(1)");
        }
    );
    },

    /**
     * beforeDropFile
     */
    beforeDropFile: (file) => {
        if (file.file.type !== "application/json") {
            Toast.fire(
                {
                    position: 'center',
                    timeout: false,
                    icon: "error",
                    title: wp.i18n.__("FlexStock: Ops! Invalid file type", "stock-sync-with-google-sheet-for-woocommerce"),
                    content: wp.i18n.__("FlexStock: Only valid JSON file with valid Google Service Account Credential is allowed", "stock-sync-with-google-sheet-for-woocommerce"),
                }
            );

            Setup.state.pond.removeFiles();
            return false;
        }
        return true;
    },

    /**
     * Sync Google Sheet
     */
    async syncGoogleSheet() {
        const spinnerUrl = `${ssgsw_script.site_url}/wp-admin/images/spinner.gif`;
        
        // Set class state for syncing (using your original code's style)
        if (this.state) {
            this.state.syncingGoogleSheet = true; 
        }

        // Show initial loading message (Using your original notice style)
        Vn.fire({
            position: "center",
            timeout: false,
            icon: "info",
            title: wp.i18n.__("FlexStock: Syncing Products to Google Sheet", "stock-sync-with-google-sheet-for-woocommerce"),
            content: `
                <div class="ssgsw_progress_bar_wrap">
                    <img src="${spinnerUrl}" alt="${wp.i18n.__("Loading...", "stock-sync-with-google-sheet-for-woocommerce")}" style="margin-top: -5px; margin-right: 2px;" />
                    <strong>${wp.i18n.__("Syncing data to the sheet.", "stock-sync-with-google-sheet-for-woocommerce")}</strong>
                </div>
                <p style="text-align: center"><strong>${wp.i18n.__("Please wait...", "stock-sync-with-google-sheet-for-woocommerce")}</strong></p>
            `,
        });

        // You might want to add button loading here if this function is called by a button,
        // but since the original function didn't include it, we'll keep it clean.
        
        try {
            // 1. Initial sync request
            const syncResponse = await Ajax.post("ssgsw_sync_sheet");
          
            // Use the multi-site logic if the response is successful and contains data
            if (syncResponse.success) {
                let totalSyncedProducts = 0;
                let totalProductsAcrossAllSites = 0;
                let indexNumber = 1;
                const batchSize = 1000; // Using 1000, as it was in the multi-site code
               
                // Calculate the total product count across all sites.
                for (const site of syncResponse.data) {
                    totalProductsAcrossAllSites += parseInt(site.product, 10);
                }

                let successCount = 0; 

                // 2. Loop through each site and process batches (Multi-Site/Vendor Logic)
                for (const site of syncResponse.data) {
                    const siteUrl = site.url;
                    const siteToken = site.token;
                    const totalItems = parseInt(site.product, 10);

                    let offset = 0;
                    // Note: No errorCount tracking used here to maintain simplicity of multi-site logic
                    while (offset < totalItems) {
                        const batchResponse = await Ajax.post("ssgsw_sync_batch_to_sheet", {
                            offset,
                            batchSize,
                            index_number: indexNumber,
                            site_url: siteUrl, // Pass site info for multi-site context
                            site_token: siteToken // Pass site info for multi-site context
                        });

                        if (batchResponse.success) {
                            totalSyncedProducts += batchResponse.data.count;
                            indexNumber += batchResponse.data.count;
                            successCount++; 

                            // Update total progress based on ALL sites
                            const currentProgress = (totalSyncedProducts / totalProductsAcrossAllSites) * 100;
                            const totalProgress = currentProgress.toFixed(2);
                            
                            // Update progress bar notice (using the original notice format)
                            Vn.fire({
                                position: "center",
                                timeout: false,
                                icon: "info",
                                title: wp.i18n.__("FlexStock: Syncing Products to Google Sheet", "stock-sync-with-google-sheet-for-woocommerce"),
                                content: `
                                    <div class="ssgsw_progress_bar_wrap">
                                        <img src="${spinnerUrl}" alt="${wp.i18n.__("Loading...", "stock-sync-with-google-sheet-for-woocommerce")}" style="margin-top: -5px; margin-right: 2px;" />
                                        <progress id="ssgsw_progress_bar_3" value="${totalProgress}" max="100"></progress>
                                        <strong style="margin-left: 3px; margin-top: -2px">${totalProgress}%</strong>
                                    </div>
                                    <p style="text-align: center"><strong>${wp.i18n.__("Please wait...", "stock-sync-with-google-sheet-for-woocommerce")}</strong></p>
                                `,
                            });
                            
                            offset += batchSize;
                        } else {
                            // Handle batch error
                            Vn.error(wp.i18n.sprintf(wp.i18n.__('FlexStock: Error syncing batch from %s: %s', 'stock-sync-with-google-sheet-for-woocommerce'), siteUrl, batchResponse.message));
                            offset += batchSize; // Move to next batch to prevent getting stuck
                        }
                    }
                }

                // 3. Final Success/Error Handling (Based on total items synced)
                if (totalSyncedProducts > 0) {
                    Vn.success(wp.i18n.__("FlexStock: Synced on Google Sheet!", "stock-sync-with-google-sheet-for-woocommerce"));
                    if (typeof this.nextScreen === 'function') {
                        this.nextScreen();
                    }
                } else {
                    Vn.fire({
                        position: "center",
                        timeout: false,
                        icon: "error",
                        title: wp.i18n.__("FlexStock: Ops!", "stock-sync-with-google-sheet-for-woocommerce"),
                        content: wp.i18n.__("FlexStock: No products were synced or an unknown error occurred.", "stock-sync-with-google-sheet-for-woocommerce"),
                    });
                }

            } else {
                // Handle initial sync request failure or empty data
                Vn.fire({
                    position: "center",
                    timeout: false,
                    icon: "error",
                    title: wp.i18n.__("FlexStock: Ops!", "stock-sync-with-google-sheet-for-woocommerce"),
                    content: wp.i18n.sprintf(wp.i18n.__("FlexStock: %s", "stock-sync-with-google-sheet-for-woocommerce"), syncResponse.message || wp.i18n.__("Something went wrong during the initial sync request.", "stock-sync-with-google-sheet-for-woocommerce")),
                });
            }
        } catch (error) {
            console.error("Error syncing Google Sheet:", error);
            Vn.fire({
                position: "center",
                timeout: false,
                icon: "error",
                title: wp.i18n.__("FlexStock: Ops!", "stock-sync-with-google-sheet-for-woocommerce"),
                content: wp.i18n.__("FlexStock: An unexpected error occurred", "stock-sync-with-google-sheet-for-woocommerce"),
            });
        } finally {
            // 4. Reset State (Exactly as requested)
            if (this.state) {
                this.state.syncingGoogleSheet = false;
            }
        }
    },
    /**
     * viewGoogleSheet
     */
    viewGoogleSheet() {
        window.open(this.option.spreadsheet_url, "_blank"); 
    },

    /**
     * Play YouTube videos
     */
    playVideos() {
        const plays = document.querySelectorAll("div[data-play]");
        const getIframe = (videoId) => {
            return `<iframe width="100%" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        };

        plays.forEach(
            (play) => {
                play.addEventListener(
                "click", (e) => {
                        const parent = e.target.closest("div[data-play]");
                        let videoUrl = parent.getAttribute("data-play");
                        // Log(videoUrl);
                        videoUrl = videoUrl.match(
                            /(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/
                        );
                const videoId = videoUrl[1] || "";
                const container = parent.querySelector("div");
                if (container) { return;
                }
                parent.innerHTML = getIframe(videoId);
                parent.classList.remove("play-icon");
                }
            );
            }
        );
    },
};

export default () => Setup;
