import { useEffect, useState } from "preact/hooks";
import { URL, catcher_async, fetch_json } from "utils";
import { Database } from "types";
import Conv from "components/Conv.tsx";
import WithStyleSheet from "components/WithStyleSheet.tsx";
import AddMsg from "components/AddMsg.tsx";
import PresetSelector from "components/PresetSelector.tsx";
import PresetCreator from "components/PresetCreator.tsx";
import { fetch_db } from "../common/db.ts";

const UPDATE_DB_INTERVAL_MS = 3000;

export default function Interactive({
    conv,
    db,
}: {
    conv: string;
    db: Database;
}) {
    const [database, setDatabase] = useState(db);
    const conv_ = database.conversations[conv];
    useEffect(() => {
        const interval = setInterval(updateDB, UPDATE_DB_INTERVAL_MS);
        return () => clearInterval(interval);
    }, []);

    const [preset, setPreset] = useState("default");

    const [creating, setCreating] = useState("preset");
    const [fg, setFg] = useState("black");
    const [bg, setBg] = useState("");
    const [font, setFont] = useState("");

    async function updateDB() {
        (await fetch_db()).map(db => setDatabase(db));
    }

    function select_preset(s: string) {
        setPreset(s);
        setCreating(s);
        setFg(conv_.presets[s].fg);
        setBg(conv_.presets[s].bg ?? "");
        setFont(conv_.presets[s].font ?? "");
    }

    return (
        <>
            <WithStyleSheet href="/Interactive.css" />
            <Conv conv={conv} db={database}>
                <AddMsg
                    preset={preset}
                    db={database}
                    conv={conv_}
                    onsubmit={async function (msg) {
                        await fetch(`${URL}/api/conv/${conv}`, {
                            method: "PUT",
                            body: JSON.stringify(msg),
                        });
                        updateDB();
                    }}
                />
                <PresetSelector
                    selected={preset}
                    setPreset={select_preset}
                    db={database}
                    conv={conv_}
                />
                <PresetCreator
                    conv={conv}
                    name={creating}
                    setName={setCreating}
                    onsubmit={updateDB}
                    {...{ fg, setFg, bg, setBg, font, setFont }}
                />
                <GoToStaticPage conv={conv} />
            </Conv>
        </>
    );
}

function GoToStaticPage({ conv }: { conv: string }) {
    return (
        <footer>
            <a href={`/${conv}`} className="back-to-static">
                Go to static page
            </a>
        </footer>
    );
}
