import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { json } from "@codemirror/lang-json";
import { Button, ErrorBox, FormItem, Input, Styles, useFetch, useToast } from "@vertesia/ui/core";
import { useUserSession } from "@vertesia/ui/session";
import { CodeMirrorEditor, GeneratedForm, ManagedObject } from "@vertesia/ui/widgets";
import { basicSetup } from "codemirror";
import { useMemo, useRef, useState } from "react";
import { SelectContentType, stringifyTableLayout } from "../types";
const extensions = [basicSetup, json()];
export function EditCollectionView({ refetch, collection }) {
    const typeId = collection.type?.id;
    const tableLayoutRef = useRef(undefined);
    const toast = useToast();
    const { client } = useUserSession();
    const [isUpdating, setUpdating] = useState(false);
    const [metadata, setMetadata] = useState({
        name: collection.name,
        description: collection.description || "",
        query: collection.query ? JSON.stringify(collection.query, null, 2) : "",
        tags: collection.tags || [],
        type: collection.type?.id || "",
        allowed_types: collection.allowed_types || [],
    });
    const tableLayoutValue = useMemo(() => {
        return stringifyTableLayout(collection.table_layout);
    }, [collection.table_layout]);
    const onSubmit = () => {
        const query = metadata.query ? JSON.parse(metadata.query) : undefined;
        const payload = {
            name: metadata.name,
            description: metadata.description,
            query: query,
            tags: metadata.tags,
            type: metadata.type,
            allowed_types: metadata.allowed_types,
        };
        let error;
        if (!payload.name) {
            error = "Name is required";
        }
        if (!payload.type) {
            payload.type = null;
        }
        if (error) {
            toast({
                title: "Validation failed",
                description: error,
                status: "error",
                duration: 5000,
            });
        }
        if (tableLayoutRef.current) {
            const layout = tableLayoutRef.current.getValue();
            if (layout) {
                try {
                    payload.table_layout = JSON.parse(layout);
                }
                catch (err) {
                    toast({
                        title: "Invalid Table Layout",
                        description: err.message,
                        status: "error",
                        duration: 5000,
                    });
                    return;
                }
            }
            else {
                payload.table_layout = null;
            }
        }
        setUpdating(true);
        client.store.collections
            .update(collection.id, payload)
            .then(() => {
            refetch();
            toast({
                title: "Collection updated",
                description: "Collection has been updated successfully",
                status: "success",
                duration: 3000,
            });
        })
            .catch((err) => {
            toast({
                title: "Failed to update collection",
                description: err.message,
                status: "error",
                duration: 5000,
            });
        })
            .finally(() => {
            setUpdating(false);
        });
    };
    const setField = (name, value) => {
        setMetadata({
            ...metadata,
            [name]: value,
        });
    };
    return (_jsxs("div", { className: "flex flex-col gap-4 py-2", children: [_jsx(FormItem, { label: "Name", required: true, children: _jsx(Input, { value: metadata.name, onChange: (v) => setField("name", v) }) }), _jsx(FormItem, { label: "Description", children: _jsx("textarea", { className: Styles.INPUT, value: metadata.description, onChange: (e) => setField("description", e.target.value) }) }), !collection.dynamic &&
                _jsx(FormItem, { label: "Allowed Content Types", description: "Select which content types can be added to the collection. If not set, then all content types are allowed.", children: _jsx(SelectContentType, { defaultValue: metadata.allowed_types || null, onChange: (v) => {
                            if (Array.isArray(v)) {
                                setField("allowed_types", v.map(type => type.id));
                            }
                            else {
                                setField("allowed_types", v ? [v.id] : []);
                            }
                        }, isClearable: true, multiple: true }) }), collection.dynamic && (_jsx(FormItem, { label: "Query", description: "Define the query to dynamically fetch content for the collection.", children: _jsx("textarea", { className: Styles.INPUT, value: metadata.query, onChange: (e) => setField("query", e.target.value) }) })), _jsx(FormItem, { label: "Table Layout", description: "Define a custom layout for displaying the collection in tables.", children: _jsx(CodeMirrorEditor, { className: "border-1 rounded-md border-border", value: tableLayoutValue, extensions: extensions, editorRef: tableLayoutRef }) }), _jsx(FormItem, { label: "Type", description: "Select a content type to assign custom properties and data to the collection.", children: _jsx(SelectContentType, { defaultValue: metadata.type || null, onChange: (v) => {
                        if (Array.isArray(v)) {
                            setField("type", v.length > 0 ? v[0].id : null);
                        }
                        else {
                            setField("type", v?.id || null);
                        }
                    }, isClearable: true }) }), _jsx(Button, { size: "lg", className: "w-min my-4", isDisabled: isUpdating, onClick: onSubmit, children: "Save Metadata" }), typeId && _jsx(PropertiesEditor, { typeId: typeId, collection: collection })] }));
}
function PropertiesEditor({ typeId, collection }) {
    const { client } = useUserSession();
    const { data: type, error } = useFetch(() => client.store.types.retrieve(typeId), [typeId]);
    if (error) {
        return _jsx(ErrorBox, { title: "Failed to load type", children: error.message });
    }
    return (_jsx(Section, { title: "Properties", children: type && _jsx(PropertiesForm, { collection: collection, schema: type.object_schema }) }));
}
function PropertiesForm({ schema = {}, collection }) {
    const { client } = useUserSession();
    const toast = useToast();
    const object = useMemo(() => new ManagedObject(schema, collection.properties || {}), [schema, collection]);
    const [isUpdating, setIsUpdating] = useState(false);
    const _onSave = (data) => {
        const payload = { properties: data || {} };
        setIsUpdating(true);
        client.store.collections
            .update(collection.id, payload)
            .then(() => {
            toast({
                title: "Collection properties updated",
                description: "Collection has been updated successfully",
                status: "success",
                duration: 3000,
            });
        })
            .catch((err) => {
            toast({
                title: "Failed to update collection properties",
                description: err.message,
                status: "error",
                duration: 5000,
            });
        })
            .finally(() => {
            setIsUpdating(false);
        });
    };
    return (_jsx(GeneratedForm, { object: object, onSubmit: _onSave, children: _jsx(Button, { size: "lg", isLoading: isUpdating, className: "my-4", variant: "primary", type: "submit", children: "Save Properties" }) }));
}
function Section({ children, title }) {
    return (_jsxs("div", { className: "my-4", children: [_jsx("div", { className: "text-lg text-gray-700 font-semibold border-b border-b-gray-300 py-2 mb-4", children: title }), children] }));
}
//# sourceMappingURL=EditCollectionView.js.map