"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } 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);
    const [error, setError] = useState();
    const activeSiteName = context?.getActiveSlotContext()?.primaryPageViewContext?.site?.name;
    useEffect(() => {
        if (!activeSiteName)
            return;
        setSiteName(activeSiteName);
    }, [context?.activeSlotId, activeSiteName]);
    useEffect(() => {
        const loadSites = async () => {
            setLoading(true);
            setError(undefined);
            try {
                const sites = await getSites();
                if (sites.data)
                    setSites(sites.data);
            }
            catch {
                setError("Failed to load dictionary sites");
            }
            finally {
                setLoading(false);
            }
        };
        loadSites();
    }, []);
    const currentItemLanguage = context?.currentItemDescriptor?.language;
    useEffect(() => {
        if (!siteName || !currentItemLanguage)
            return;
        const loadDictionary = async (site, language) => {
            setLoading(true);
            setError(undefined);
            try {
                const dictionary = await getDictionary(site, language);
                setDictionary(dictionary);
            }
            catch {
                setDictionary(null);
                setError("Failed to load dictionary");
            }
            finally {
                setLoading(false);
            }
        };
        loadDictionary(siteName, currentItemLanguage);
    }, [siteName, currentItemLanguage]);
    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 (error)
            return _jsx(CenteredMessage, { children: error });
        if (!dictionary)
            return _jsx(CenteredMessage, { children: "No dictionary found" });
        if (Object.keys(dictionary).length === 0 &&
            renderedDictionaryKeys?.length === 0)
            return _jsx(CenteredMessage, { children: "No dictionary entries" });
        return (_jsxs(_Fragment, { children: [_jsxs("section", { "data-testid": "dictionary-rendered-keys", 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("section", { "data-testid": "dictionary-unknown-keys", children: _jsx(UnknownKeysTable, { entries: unknownKeys }) }), _jsxs("section", { "data-testid": "dictionary-other-keys", children: [_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, { "data-testid": "dictionary-site-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, "before:border-border-default after:border-border-default flex items-center py-1 text-sm font-bold before:me-6 before:flex-1 before:border-t after:ms-6 after:flex-1 after:border-t"), 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, { "data-testid": `dictionary-input-${entry.key}`, value: value, disabled: refresh, onChange: (e) => setValue(e.target.value), autoFocus: true }), !refresh && (_jsx(Button, { "data-testid": `dictionary-apply-${entry.key}`, 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, { strokeWidth: 1, 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", { "data-testid": `dictionary-translation-${entry.key}`, 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, rowTestId: (entry) => `dictionary-entry-${entry.key}` }) }));
}
function UnknownKeysTable({ entries }) {
    const columns = [{ body: (entry) => entry, header: "Key" }];
    return (_jsx("div", { children: _jsx(SimpleTable, { items: entries, columns: columns, rowTestId: (entry) => `dictionary-unknown-${entry}` }) }));
}
//# sourceMappingURL=DictionaryEditor.js.map