import { useQuery } from "react-query";
import { ChannelInfo, fetchGuildChannels, fetchGuildTodos } from "../../api";
import { useGuild } from "../App/useGuild";
import { Todo } from "../Todo";
import { Todo as TodoT } from "../../api";
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));
    const globalTodos = sortedTodos.filter((todo) => todo.channel_id === null);

    return (
        <>
            <strong>Create todo list</strong>
            <CreateTodo channel={null} showSelector={true} />
            <strong>Todo lists</strong>
            {globalTodos.length > 0 && (
                <>
                    <h2>Server</h2>
                    {globalTodos.map((todo) => (
                        <>
                            <Todo todo={todo} key={todo.id} />
                        </>
                    ))}
                    <CreateTodo channel={null} />
                </>
            )}
            {channels
                .map(
                    (channel) =>
                        [channel, sortedTodos.filter((todo) => todo.channel_id === channel.id)] as [
                            ChannelInfo,
                            TodoT[],
                        ],
                )
                .filter(([_, todos]) => todos.length > 0)
                .map(([channel, todos]) => {
                    return (
                        <>
                            <h2>#{channel.name}</h2>
                            {todos.map((todo) => (
                                <>
                                    <Todo todo={todo} key={todo.id} />
                                </>
                            ))}
                            <CreateTodo channel={channel.id} />
                        </>
                    );
                })}
        </>
    );
};
