import { useState } from "preact/hooks";
import { Modal } from "../../Modal";
import { useMutation, useQueryClient } from "react-query";
import { useReminder } from "../ReminderContext";
import { deleteReminder } from "../../../api";
import { useParams } from "wouter";
import { useFlash } from "../../App/FlashContext";
import { useGuild } from "../../App/useGuild";

export const DeleteButton = () => {
    const [modalOpen, setModalOpen] = useState(false);

    return (
        <>
            <button
                class="button is-danger delete-reminder"
                onClick={() => {
                    setModalOpen(true);
                }}
            >
                Delete
            </button>
            {modalOpen && <DeleteModal setModalOpen={setModalOpen}></DeleteModal>}
        </>
    );
};

const DeleteModal = ({ setModalOpen }) => {
    const [reminder] = useReminder();
    const guild = useGuild();

    const flash = useFlash();
    const queryClient = useQueryClient();
    const mutation = useMutation({
        ...deleteReminder(),
        onSuccess: () => {
            flash({
                message: "Reminder deleted",
                type: "success",
            });
            if (guild) {
                queryClient.invalidateQueries({
                    queryKey: ["GUILD_REMINDERS", guild],
                });
            } else {
                queryClient.invalidateQueries({
                    queryKey: ["USER_REMINDERS"],
                });
            }
            setModalOpen(false);
        },
    });

    return (
        <Modal setModalOpen={setModalOpen} title={"Delete Reminder"}>
            <>
                <p>This reminder will be permanently deleted. Are you sure?</p>
                <br></br>
                <div class="has-text-centered">
                    <button
                        class="button is-danger"
                        onClick={() => {
                            mutation.mutate(reminder);
                        }}
                        disabled={mutation.isLoading}
                    >
                        Delete
                    </button>
                    <button
                        class="button is-light close-modal"
                        onClick={() => {
                            setModalOpen(false);
                        }}
                    >
                        Cancel
                    </button>
                </div>
            </>
        </Modal>
    );
};
