import { useState } from "preact/hooks";
import { useMutation, useQueryClient } from "react-query";
import { patchGuildReminder } from "../../../api";
import { useParams } from "wouter";
import { ICON_FLASH_TIME } from "../../../consts";
import { DeleteButton } from "./DeleteButton";
import { useReminder } from "../ReminderContext";
import { useFlash } from "../../App/FlashContext";

export const EditButtonRow = () => {
    const { guild } = useParams();
    const [reminder] = useReminder();

    const [recentlySaved, setRecentlySaved] = useState(false);
    const queryClient = useQueryClient();

    const flash = useFlash();

    const mutation = useMutation({
        ...patchGuildReminder(guild),
        onSuccess: () => {
            queryClient.invalidateQueries({
                queryKey: ["GUILD_REMINDERS", guild],
            });
            setRecentlySaved(true);
            setTimeout(() => {
                setRecentlySaved(false);
            }, ICON_FLASH_TIME);
        },
        onError: (error) => {
            flash(error);
        },
    });

    return (
        <div class="button-row-edit">
            <button
                class="button is-success save-btn"
                onClick={() => {
                    mutation.mutate(reminder);
                }}
                disabled={mutation.isLoading}
            >
                <span>Save</span>{" "}
                {mutation.isLoading ? (
                    <span class="icon">
                        <i class="fas fa-spin fa-cog"></i>
                    </span>
                ) : recentlySaved ? (
                    <span class="icon">
                        <i class="fas fa-check"></i>
                    </span>
                ) : (
                    <span class="icon">
                        <i class="fas fa-save"></i>
                    </span>
                )}
            </button>
            <button
                class="button is-warning"
                onClick={() => {
                    mutation.mutate({
                        ...reminder,
                        enabled: !reminder.enabled,
                    });
                }}
                disabled={mutation.isLoading}
            >
                {reminder.enabled ? "Disable" : "Enable"}
            </button>
            <DeleteButton />
        </div>
    );
};
