import { useEffect, useState } from "react";
import { init, Model, IronCalc } from "@ironcalc/workbook";
import initConvert, { xlsx_to_ironcalc, ironcalc_to_xlsx } from "convert";

import "@ironcalc/workbook/style.css";

export function App() {
    const [model, setModel] = useState(null);
    const [readOnly, setReadOnly] = useState(false);

    useEffect(() => {
        let m = null;
        const onMessage = async ({ data }) => {
            switch (data?.type) {
            case "xlsx:load": {
                m = Model.from_bytes(xlsx_to_ironcalc(
                    new Uint8Array(data.buffer),
                    data.name || "workbook.xlsx",
                ), "en");
                setReadOnly(!!data.readOnly);
                setModel(m);
                break;
            }
            case "xlsx:save:request":
                const xlsx = ironcalc_to_xlsx(m.toBytes());
                window.parent.postMessage(
                    { type: "xlsx:save:response", buffer: xlsx.buffer },
                    "*",
                    [xlsx.buffer],
                );
                break;
            }
        };
        Promise.all([init(), initConvert()]).then(() => {
            window.addEventListener("message", onMessage);
            window.parent.postMessage({ type: "xlsx:ready" }, "*");
        });
        return () => window.removeEventListener("message", onMessage);
    }, []);

    if (!model) return null;
    return (
        <div style={{ height: "100%" }}
             onKeyDownCapture={() => window.parent.postMessage({ type: "xlsx:change" }, "*")}
             onPaste={() => window.parent.postMessage({ type: "xlsx:change" }, "*")}>
            <IronCalc model={model} />
        </div>
    );
}
