import React, {FC, useEffect, useState} from "react";
import {colors} from "./Colors";
import {EmulatedButton} from "./EmulatedButton";
import {__} from "../globals";
import {useNodesStore} from "./store";
import {AppExporter} from "./export/AppExporter";
import {GroveExporter} from "./export/GroveExporter";
import {ExportableDataFormatPreset, ExportableDataFormatServer} from "./export/AppImporter";
import js from "@eslint/js";
import toast from "react-hot-toast";
import classNames from "classnames";
import {Superballs} from 'ldrs/react'

import 'ldrs/react/Superballs.css'


export type SaveButtonProps = {
    compact?: boolean;
}

export const SaveButton: FC<SaveButtonProps> = ({compact = false}) => {
    const [isSaving, setIsSaving] = useState(false);

    useEffect(() => {
        // Check if WordPress success notice exists in the DOM
        const wordpressNotice = document.querySelector('.notice.notice-success.updated');
        if (wordpressNotice) {
            showSavedNotification();
        }
    }, []);

    return <EmulatedButton
        className={classNames(
            `font-semibold ${colors.blue.background(100)} ${colors.blue.text(10)} border-px border-blue-shade-100 rounded-full flex items-center text-center justify-center gap-2 transition-all duration-200 hover:scale-[1.02] focus:scale-[.90] active:scale-[.90] scale-100 active:ring-[2px] active:ring-blue-normal active:ring-offset-4 active:ring-opacity-20`,
            {
                'text-2x w-full px-8 py-1 h-9': !compact,
                'text-1x px-5 py-1 h-8': compact,
            }
        )}
        onClick={() => {
            if (!isSaving) {
                setIsSaving(true);
                save();
            }
        }}>
        {false && <div
            className={`relative min-w-4 min-h-4 max-w-4 max-h-4 flex items-center justify-center rounded-5 ${colors.blue.background(10)} ${colors.blue.text(100)}`}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                 className="min-w-[12px] min-h-[12px] max-w-[12px] max-h-[12px]">
                <path
                    d="M5.507 4.048A3 3 0 0 1 7.785 3h8.43a3 3 0 0 1 2.278 1.048l1.722 2.008A4.533 4.533 0 0 0 19.5 6h-15c-.243 0-.482.02-.715.056l1.722-2.008Z"/>
                <path fillRule="evenodd"
                      d="M1.5 10.5a3 3 0 0 1 3-3h15a3 3 0 1 1 0 6h-15a3 3 0 0 1-3-3Zm15 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm2.25.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM4.5 15a3 3 0 1 0 0 6h15a3 3 0 1 0 0-6h-15Zm11.25 3.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM19.5 18a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z"
                      clipRule="evenodd"/>
            </svg>
        </div>}
        <div className={classNames('flex transition-all duration-300 ease', {
            'scale-[2] opacity-0': !isSaving,
            'opacity-100 scale-100': isSaving,
        })}>
            <Superballs
                size="22"
                speed="1.20"
                color="white"
            />
        </div>
        <span className={classNames('absolute left-1/2 top-1/2 translate-y-[-50%] translate-x-[-50%]  transition-all duration-200', {
            'opacity-0 scale-95': isSaving,
            'opacity-100 scale-100': !isSaving,
        })}>{__('Save')}</span>
    </EmulatedButton>
}

function save() {
    const state = useNodesStore.getState();
    const appExporter = new AppExporter(state, new GroveExporter(state))

    let {version, grove, testablePartialRelations, preloadedData, preconditions, predates, autoApply, model} = appExporter.export('server') as ExportableDataFormatServer
    const serializedPreconditions = JSON.stringify(preconditions ?? null)
    const serializedPredates = JSON.stringify(predates ?? null)

    return triggerSaveWithData({
        version: version.toString(),
        grove: JSON.stringify(grove),
        testable_partial_relations: JSON.stringify(testablePartialRelations),
        preloaded_data: JSON.stringify(preloadedData),
        preconditions: serializedPreconditions,
        predates: serializedPredates,
        coupon_auto_apply_is_enabled: autoApply,
        model
    });
}

function triggerSaveWithData(dataEntries: Record<string, string | undefined>) {
    const form = document.getElementById('post') as HTMLFormElement;

    if (form) {
        const originalSubmit = form.onsubmit;

        form.onsubmit = function (e) {
            for (let [key, value] of Object.entries(dataEntries)) {
                if (value === undefined) {
                    continue;
                }
                key = `couponsplus_${key}`;
                let input = document.getElementById(`cp-hidden-${key}`) as HTMLInputElement;

                if (input) {
                    input.value = value;
                } else {
                    input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = value;
                    input.id = `cp-hidden-${key}`;
                    form.appendChild(input);
                }
            }

            form.onsubmit = originalSubmit;

            return true;
        };

        const publishButton = document.getElementById('publish') as HTMLButtonElement;

        if (publishButton) {
            publishButton.click();
        }
    }
}

function showSavedNotification() {
    toast.custom((t) => (
        <div className={`relative bg-gray-450 text-white flex items-center gap-3 rounded-2 px-4 py-2 z-[10000000] min-w-35 transition-all duration-300 ease-in-out transform ${
            t.visible ? 'opacity-100 translate-y-0 scale-100' : 'opacity-0 translate-y-2 scale-95'
        }`}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="min-w-6 min-h-6 max-w-6 max-h-6">
                <path fillRule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z" clipRule="evenodd" />
            </svg>
            <span>{__('Saved')}</span>
        </div>
    ), {
        id: 'saved-notification',
        duration: 3000,
    })
}
