import { useQuery } from "react-query";
import { fetchGuildChannels, fetchGuildTodos } from "../../api";
import { useGuild } from "../App/useGuild";
import { Todo } from "../Todo";
import { Loader } from "../Loader";
import { CreateTodo } from "../Todo/CreateTodo";

export const GuildTodos = () => {
    const guild = useGuild();

    const { isFetched, data: guildTodos } = useQuery(fetchGuildTodos(guild));
    const { data: channels } = useQuery(fetchGuildChannels(guild));

    if (!isFetched || !channels) {
        return <Loader />;
    }

    const sortedTodos = guildTodos
        .sort((a, b) => (a.id > b.id ? -1 : 1))
        .sort((a, b) => (a.channel_id < b.channel_id ? 0 : 1));
    let prevChannel;

    return (
        <>
            <strong>Create Todo</strong>
            <CreateTodo />
            <br />
            <strong>Todo list</strong>
            {sortedTodos.map((todo) => {
                if (prevChannel !== todo.channel_id) {
                    prevChannel = todo.channel_id;
                    if (todo.channel_id === null) {
                        return (
                            <>
                                <h2>Server Todos</h2>
                                <Todo todo={todo} key={todo.id} />
                            </>
                        );
                    } else {
                        const channel = channels.find((ch) => ch.id === todo.channel_id);
                        return (
                            <>
                                <h2>#{channel.name} Todos</h2>
                                <Todo todo={todo} key={todo.id} />
                            </>
                        );
                    }
                }

                return <Todo todo={todo} key={todo.id} />;
            })}
        </>
    );
};
