import { deleteGuildTodo, patchGuildTodo, Todo as TodoT, UpdateTodo } from "../../api";

import "./index.scss";
import { useMutation, useQueryClient } from "react-query";
import { useFlash } from "../App/FlashContext";
import { useGuild } from "../App/useGuild";
import { useState } from "preact/hooks";
import { ICON_FLASH_TIME } from "../../consts";

type Props = {
    todo: TodoT;
};

export const Todo = ({ todo }: Props) => {
    const guild = useGuild();

    const [updatedTodo, setUpdatedTodo] = useState<UpdateTodo>({ value: todo.value });
    const [recentlySaved, setRecentlySaved] = useState(false);

    const flash = useFlash();

    const queryClient = useQueryClient();
    const deleteMutation = useMutation({
        ...deleteGuildTodo(guild),
        onSuccess: () => {
            flash({
                message: "Todo deleted",
                type: "success",
            });
            queryClient.invalidateQueries({
                queryKey: ["GUILD_TODOS", guild],
            });
        },
    });

    const patchMutation = useMutation({
        ...patchGuildTodo(guild),
        onError: (error) => {
            flash({
                message: `An error occurred: ${error}`,
                type: "error",
            });
        },
        onSuccess: (response) => {
            if (response.data.error) {
                setRecentlySaved(false);
                flash({ message: response.data.error, type: "error" });
            } else {
                setRecentlySaved(true);
                setTimeout(() => {
                    setRecentlySaved(false);
                }, ICON_FLASH_TIME);
            }
        },
    });

    return (
        <div class="todo">
            <textarea
                class="input todo-input"
                value={updatedTodo.value}
                onInput={(ev) =>
                    setUpdatedTodo({
                        value: ev.currentTarget.value,
                    })
                }
            />
            <button
                onClick={() => patchMutation.mutate({ id: todo.id, todo: updatedTodo })}
                class="button is-success save-btn"
            >
                <span class="icon">
                    {recentlySaved ? <i class="fa fa-check"></i> : <i class="fa fa-save"></i>}
                </span>
            </button>
            <button onClick={() => deleteMutation.mutate(todo.id)} class="button is-danger">
                <span class="icon">
                    <i class="fa fa-trash"></i>
                </span>
            </button>
        </div>
    );
};
