import { useQuery } from "react-query";
import { fetchGuildInfo } from "../../api";
import { GuildError } from "./GuildError";
import { createPortal, PropsWithChildren } from "preact/compat";
import { Import } from "../Import";
import { useGuild } from "../App/useGuild";
import { Link } from "wouter";
import { usePathname } from "wouter/use-browser-location";

import "./index.scss";

export const Guild = ({ children }: PropsWithChildren) => {
    const guild = useGuild();
    const { isSuccess, data: guildInfo } = useQuery(fetchGuildInfo(guild));

    if (!isSuccess) {
        return <></>;
    } else if (guildInfo.error) {
        return <GuildError />;
    } else {
        const importModal = createPortal(<Import />, document.getElementById("bottom-sidebar"));
        const path = usePathname();

        return (
            <>
                {importModal}
                <div class="page-links">
                    <Link
                        class={`button is-outlined is-success is-small ${path.endsWith("reminders") && "is-focused"}`}
                        href={`/${guild}/reminders`}
                    >
                        <span>Reminders</span>
                        <span class="icon">
                            <i class="fa fa-chevron-right"></i>
                        </span>
                    </Link>
                    <Link
                        class={`button is-outlined is-success is-small ${path.endsWith("todos") && "is-focused"}`}
                        href={`/${guild}/todos`}
                    >
                        <span>Todo lists</span>
                        <span class="icon">
                            <i class="fa fa-chevron-right"></i>
                        </span>
                    </Link>
                </div>
                {children}
            </>
        );
    }
};
