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

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

    const [recentlyCreated, setRecentlyCreated] = useState(false);

    const flash = useFlash();
    const queryClient = useQueryClient();
    const mutation = useMutation({
        ...postGuildReminder(guild),
        onSuccess: (data) => {
            if (data.error) {
                flash(data.error);
            } else {
                queryClient.invalidateQueries({
                    queryKey: ["GUILD_REMINDERS", guild],
                });
                setRecentlyCreated(true);
                setTimeout(() => {
                    setRecentlyCreated(false);
                }, ICON_FLASH_TIME);
            }
        },
    });

    return (
        <div class="button-row">
            <div class="button-row-reminder">
                <button
                    class="button is-success"
                    onClick={() => {
                        mutation.mutate(reminder);
                    }}
                >
                    <span>Create Reminder</span>{" "}
                    {mutation.isLoading ? (
                        <span class="icon">
                            <i class="fas fa-spin fa-cog"></i>
                        </span>
                    ) : recentlyCreated ? (
                        <span class="icon">
                            <i class="fas fa-check"></i>
                        </span>
                    ) : (
                        <span class="icon">
                            <i class="fas fa-sparkles"></i>
                        </span>
                    )}
                </button>
            </div>
            <div class="button-row-template">
                <div>
                    <button class="button is-success is-outlined">
                        <span>Create Template</span>{" "}
                        <span class="icon">
                            <i class="fas fa-file-spreadsheet"></i>
                        </span>
                    </button>
                </div>
                <div>
                    <LoadTemplate />
                </div>
            </div>
        </div>
    );
};
