import { Reminder } from "../../api";
import { useEffect, useState } from "preact/hooks";
import { EditButtonRow } from "./ButtonRow/EditButtonRow";
import { Message } from "./Message";
import { Settings } from "./Settings";
import { ReminderContext } from "./ReminderContext";
import { TopBar } from "./TopBar";
import "./styles.scss";

type Props = {
    reminder: Reminder;
    globalCollapse: boolean;
};

export const EditReminder = ({ reminder: initialReminder, globalCollapse }: Props) => {
    const [propReminder, setPropReminder] = useState(initialReminder);
    const [reminder, setReminder] = useState(initialReminder);
    const [collapsed, setCollapsed] = useState(false);

    useEffect(() => {
        setCollapsed(globalCollapse);
    }, [globalCollapse]);

    // Reminder updated from web response
    if (propReminder !== initialReminder) {
        setReminder(initialReminder);
        setPropReminder(initialReminder);
    }

    return (
        <ReminderContext.Provider value={[reminder, setReminder]} key={reminder.uid}>
            <div
                class={collapsed ? "reminderContent is-collapsed" : "reminderContent"}
                id={`reminder-${reminder.uid.slice(0, 12)}`}
            >
                <TopBar
                    isCreating={false}
                    toggleCollapsed={() => {
                        setCollapsed(!collapsed);
                    }}
                />
                <div class="columns reminder-settings">
                    <Message />
                    <Settings />
                </div>
                <EditButtonRow />
            </div>
        </ReminderContext.Provider>
    );
};
