import React, { useContext, useState } from "react";
import { LayoutBuilderCanvasContext } from "@/features/layout-builder/layout-builder-canvas-provider";

export default function SaveCloseLayoutBuilderTool() {
    const { canvas, onSave, onClose, onCancel } = useContext(LayoutBuilderCanvasContext);

    const [isSaving, setIsSaving] = useState<boolean>(false);
    const [isClosing, setIsClosing] = useState<boolean>(false);
    const [isCancelling, setIsCancelling] = useState<boolean>(false);

    const save = async () => {
        if (!canvas) {
            return;
        }

        if (isSaving || isClosing || isCancelling) {
            return;
        }

        setIsSaving(true);

        onSave && await onSave();

        setIsSaving(false);
    };

    const close = async () => {
        if (!canvas) {
            return;
        }

        if (isSaving || isClosing || isCancelling) {
            return;
        }

        setIsClosing(true);

        onClose && await onClose();

        setIsClosing(false);
    }

    const cancel = async () => {
        if (!canvas) {
            return;
        }

        if (isSaving || isClosing || isCancelling) {
            return;
        }

        setIsCancelling(true);

        onCancel && await onCancel();

        setIsCancelling(false);
    }

    return <div className="grid grid-cols-3 gap-4">
        <button
            className="bg-gray-400 text-white h-[60px] rounded-[8px] p-[.5rem]"
            onClick={async e => {
                e.preventDefault();
                await cancel();
            }}
        >
            {isCancelling ? `Cancelling...` : `Cancel`}
        </button>

        <button className="bg-dark-orange text-white h-[60px] rounded-[8px] p-[.5rem]"
            onClick={async e => {
                e.preventDefault();
                await save();
            }}
        >
            {isSaving ? `Saving...` : `Save`}
        </button>

        <button className="bg-dark-orange text-white h-[60px] rounded-[8px] p-[.5rem]"
            onClick={async e => {
                e.preventDefault();
                await save();
                await close();
            }}
        >
            {isSaving ? `Saving...` : ``}
            {isClosing ? `Closing...` : ``}
            {!isSaving && !isClosing ? `Save and Close` : ``}
        </button>
    </div>;
}
