import { useGuild } from "../../App/useGuild";
import { useReminder } from "../ReminderContext";
import { useQuery } from "react-query";
import { fetchGuildChannels, Reminder } from "../../../api";
import { useCallback } from "preact/hooks";
import { DateTime } from "luxon";
import { Name } from "../Name";

export const Guild = ({ toggleCollapsed, isCreating }) => {
    const guild = useGuild();
    const [reminder] = useReminder();

    const { isSuccess, data: guildChannels } = useQuery(fetchGuildChannels(guild));

    const channelName = useCallback(
        (reminder: Reminder) => {
            const channel = guildChannels.find((c) => c.id === reminder.channel);
            return channel === undefined ? "" : channel.name;
        },
        [guildChannels],
    );

    let days, hours, minutes, seconds;
    seconds = Math.floor(
        DateTime.fromISO(reminder.utc_time, { zone: "UTC" }).diffNow("seconds").seconds,
    );
    [days, seconds] = [Math.floor(seconds / 86400), seconds % 86400];
    [hours, seconds] = [Math.floor(seconds / 3600), seconds % 3600];
    [minutes, seconds] = [Math.floor(seconds / 60), seconds % 60];

    let string;
    if (days !== 0) {
        if (hours !== 0) {
            string = `${days} days, ${hours} hours`;
        } else {
            string = `${days} days`;
        }
    } else if (hours !== 0) {
        if (minutes !== 0) {
            string = `${hours} hours, ${minutes} minutes`;
        } else {
            string = `${hours} hours`;
        }
    } else if (minutes !== 0) {
        if (seconds !== 0) {
            string = `${minutes} minutes, ${seconds} seconds`;
        } else {
            string = `${minutes} minutes`;
        }
    } else {
        string = `${seconds} seconds`;
    }

    return (
        <div class="columns is-mobile column reminder-topbar">
            {isSuccess && <div class="invert-collapses channel-bar">#{channelName(reminder)}</div>}
            <Name />
            {!isCreating && <div class="time-bar">in {string}</div>}
            <div class="hide-button-bar">
                <button class="button hide-box" onClick={toggleCollapsed}>
                    <span class="is-sr-only">Hide reminder</span>
                    <i class="fas fa-chevron-down"></i>
                </button>
            </div>
        </div>
    );
};
