import { useState } from "preact/hooks";
import { fetchGuildChannels, Reminder } from "../../api";
import { DateTime } from "luxon";
import { CreateButtonRow } from "./ButtonRow/CreateButtonRow";
import { TopBar } from "./TopBar";
import { Message } from "./Message";
import { Settings } from "./Settings";
import { ReminderContext } from "./ReminderContext";
import { useQuery } from "react-query";
import { useParams } from "wouter";

function defaultReminder(): Reminder {
    return {
        attachment: null,
        attachment_name: null,
        avatar: null,
        channel: null,
        content: "",
        embed_author: "",
        embed_author_url: null,
        embed_color: 0,
        embed_description: "",
        embed_fields: [],
        embed_footer: "",
        embed_footer_url: null,
        embed_image_url: null,
        embed_thumbnail_url: null,
        embed_title: "",
        enabled: true,
        expires: null,
        interval_days: null,
        interval_months: null,
        interval_seconds: null,
        name: "",
        restartable: false,
        tts: false,
        uid: "",
        username: "",
        utc_time: DateTime.now(),
    };
}

export const CreateReminder = () => {
    const { guild } = useParams();

    const [reminder, setReminder] = useState(defaultReminder());
    const [collapsed, setCollapsed] = useState(false);

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

    if (isSuccess && reminder.channel === null) {
        setReminder((reminder) => ({
            ...reminder,
            channel: reminder.channel || guildChannels[0].id,
        }));
    }

    return (
        <ReminderContext.Provider value={[reminder, setReminder]}>
            <div class={collapsed ? "reminderContent is-collapsed" : "reminderContent"}>
                <TopBar
                    toggleCollapsed={() => {
                        setCollapsed(!collapsed);
                    }}
                />
                <div class="columns reminder-settings">
                    <Message />
                    <Settings />
                </div>
                <CreateButtonRow />
            </div>
        </ReminderContext.Provider>
    );
};
