"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { getDictionary, getSites } from "../services/contentService";
import { SimpleTable } from "../ui/SimpleTable";
import { Loader2 } from "lucide-react";
import { Input } from "../../components/ui/input";
import { Button } from "../../components/ui/button";
import { cn } from "../../lib/utils";
import { CenteredMessage } from "../ui/CenteredMessage";
import { Select } from "../../components/ui/select";
import { SimpleToolbar } from "../ui/SimpleToolbar";
export function DictionaryEditor({}) {
    const context = useEditContext();
    const [dictionary, setDictionary] = useState({});
    const [renderedDictionaryKeys, setRenderedDictionaryKeys] = useState();
    const [unknownKeys, setUnknownKeys] = useState();
    const [otherKeys, setOtherKeys] = useState();
    const [validKeys, setValidKeys] = useState();
    const [sites, setSites] = useState();
    const [siteName, setSiteName] = useState();
    const [loading, setLoading] = useState(false);
    useEffect(() => {
        const pageViewContext = context?.getActiveSlotContext()?.primaryPageViewContext;
        if (!pageViewContext?.site)
            return;
        setSiteName(pageViewContext.site.name);
    }, [context?.activeSlotId, context?.slotContexts]);
    useEffect(() => {
        const loadSites = async () => {
            setLoading(true);
            const sites = await getSites();
            if (sites.data)
                setSites(sites.data);
            setLoading(false);
        };
        loadSites();
    }, []);
    const currentItemDescriptor = context?.currentItemDescriptor;
    useEffect(() => {
        if (!siteName || !currentItemDescriptor)
            return;
        const loadDictionary = async (site, language) => {
            const dictionary = await getDictionary(site, language);
            setDictionary(dictionary);
        };
        loadDictionary(siteName, currentItemDescriptor.language);
    }, [siteName, currentItemDescriptor]);
    useEffect(() => {
        const findAllKeys = (component, keys) => {
            component.renderedDictionaryKeys.forEach((k) => {
                if (!keys.includes(k))
                    keys.push(k);
            });
            component.placeholders.forEach((p) => {
                p.components.forEach((c) => findAllKeys(c, keys));
            });
        };
        if (!context?.page)
            return;
        const keys = [];
        findAllKeys(context.page.rootComponent, keys);
        setRenderedDictionaryKeys(keys);
    }, [context?.page]);
    useEffect(() => {
        if (!dictionary || !renderedDictionaryKeys) {
            setValidKeys([]);
            setOtherKeys([]);
            setUnknownKeys([]);
            return;
        }
        const getEntries = (keys) => {
            const entries = Object.keys(dictionary)
                .filter((k) => keys.includes(k))
                .map((k) => ({
                key: k,
                field: dictionary[k],
                translation: dictionary[k].value,
            }));
            entries.sort((a, b) => (a.key > b.key ? -1 : 1));
            return entries;
        };
        const unknownKeys = renderedDictionaryKeys.filter((k) => !dictionary[k]);
        unknownKeys.sort((a, b) => (a > b ? -1 : 1));
        setUnknownKeys(unknownKeys);
        setValidKeys(getEntries(renderedDictionaryKeys.filter((k) => dictionary[k])));
        setOtherKeys(getEntries(Object.keys(dictionary).filter((k) => !renderedDictionaryKeys.includes(k))));
    }, [renderedDictionaryKeys, dictionary]);
    const getContent = () => {
        if (!unknownKeys || !validKeys || !otherKeys)
            return null;
        if (!siteName)
            return _jsx(CenteredMessage, { children: "No Site" });
        if (loading)
            return _jsx(CenteredMessage, { children: "Loading..." });
        if (!dictionary)
            return _jsx(CenteredMessage, { children: "No dictionary found" });
        return (_jsxs(_Fragment, { children: [_jsx(Divider, { text: "Keys rendered on this page", className: "mt-1" }), _jsx(DictionaryTable, { entries: validKeys, context: context }), _jsx(Divider, { text: "\u26A0 Unknown keys", className: "mt-6" }), _jsx(UnknownKeysTable, { entries: unknownKeys }), _jsx(Divider, { text: "Other keys", className: "mt-6" }), _jsx(DictionaryTable, { entries: otherKeys, context: context })] }));
    };
    return (_jsxs("div", { className: "flex h-full flex-col gap-1", children: [_jsxs(SimpleToolbar, { children: ["Site:", " ", _jsx(Select, { options: sites?.map((s) => ({ label: s.name, value: s.name })) || [], value: siteName, onValueChange: (value) => setSiteName(value), placeholder: "Select site" })] }), getContent()] }));
}
function Divider({ text, className }) {
    return (_jsx("div", { className: cn(className, "flex items-center py-1 text-sm font-bold before:me-6 before:flex-1 before:border-t before:border-gray-200 after:ms-6 after:flex-1 after:border-t after:border-gray-200"), children: text }));
}
function DictionaryTable({ entries, context, }) {
    const [editing, setEditing] = useState();
    const [value, setValue] = useState("");
    const [refresh, setRefresh] = useState(false);
    const modifiedFieldsContext = useFieldsEditContext();
    useEffect(() => {
        if (refresh) {
            setEditing(undefined);
            setRefresh(false);
        }
    }, [context.refreshCompletedFlag]);
    const textEditor = (entry) => {
        if (entry.field)
            return (_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx(Input, { value: value, disabled: refresh, onChange: (e) => setValue(e.target.value), autoFocus: true }), !refresh && (_jsx(Button, { size: "sm", onClick: () => {
                            setRefresh(true);
                            if (!entry.field)
                                return;
                            context?.operations.editField({
                                field: entry.field.descriptor,
                                value: value,
                                refresh: "immediate",
                            });
                        }, children: "Apply" })), refresh && _jsx(Loader2, { className: "h-5 w-5 animate-spin" })] }));
        else
            return null;
    };
    const columns = [
        { body: (entry) => entry.key, header: "Key" },
        {
            body: (entry) => {
                const modifiedField = modifiedFieldsContext?.modifiedFields.find((x) => x.fieldId === entry.field?.id &&
                    x.item.id === entry.field?.descriptor.item.id &&
                    x.item.language === entry.field?.descriptor.item.language &&
                    x.item.version === entry.field?.descriptor.item.version);
                if (editing === entry.key)
                    return textEditor(entry);
                else
                    return (_jsxs("div", { className: "min-w-ful cursor-pointer", onClick: () => {
                            if (!editing) {
                                setValue(modifiedField?.value ?? entry.translation);
                                setEditing(entry.key);
                            }
                        }, children: [modifiedField?.value ?? entry.translation, " \u00A0"] }));
            },
            header: "Translation",
        },
    ];
    return (_jsx("div", { children: _jsx(SimpleTable, { items: entries, columns: columns }) }));
}
function UnknownKeysTable({ entries }) {
    const columns = [{ body: (entry) => entry, header: "Key" }];
    return (_jsx("div", { children: _jsx(SimpleTable, { items: entries, columns: columns }) }));
}
//# sourceMappingURL=DictionaryEditor.js.map