import API from "../../Utils/API/API";
import ModelAPI from "../../Utils/ModelAPI/ModelAPI";
import { ButtonStyleType } from "../Button/Button";
import Card from "../Card/Card";
import ComponentLoader from "../ComponentLoader/ComponentLoader";
import Detail from "../Detail/Detail";
import ErrorMessage from "../ErrorMessage/ErrorMessage";
import BasicFormModal from "../FormModal/BasicFormModal";
import CustomFieldType from "../../../Types/CustomField/CustomFieldType";
import { LIMIT_PER_PROJECT } from "../../../Types/Database/LimitMax";
import IconProp from "../../../Types/Icon/IconProp";
import React, { useState } from "react";
import useAsyncEffect from "use-async-effect";
const parseDropdownOptions = (value) => {
    if (typeof value !== "string" || !value) {
        return [];
    }
    return value
        .split("\n")
        .map((line) => {
        return line.trim();
    })
        .filter((line) => {
        return line.length > 0;
    })
        .map((line) => {
        return { label: line, value: line };
    });
};
const CustomFieldsDetail = (props) => {
    const [schemaList, setSchemaList] = useState([]);
    const [error, setError] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [model, setModel] = useState(null);
    const [showModelForm, setShowModelForm] = useState(false);
    const onLoad = async () => {
        try {
            // load schema.
            setIsLoading(true);
            const schemaList = await ModelAPI.getList({
                modelType: props.customFieldType,
                query: {
                    projectId: props.projectId,
                },
                limit: LIMIT_PER_PROJECT,
                skip: 0,
                select: {
                    name: true,
                    customFieldType: true,
                    description: true,
                    dropdownOptions: true,
                },
                sort: {},
            });
            const item = await ModelAPI.getItem({
                modelType: props.modelType,
                id: props.modelId,
                select: {
                    customFields: true,
                },
            });
            setSchemaList(schemaList.data);
            setModel(item);
            setIsLoading(false);
        }
        catch (err) {
            setIsLoading(false);
            setError(API.getFriendlyMessage(err));
        }
    };
    const onSave = async (data) => {
        try {
            // load schema.
            setIsLoading(true);
            setShowModelForm(false);
            await ModelAPI.updateById({
                modelType: props.modelType,
                id: props.modelId,
                data: {
                    customFields: data,
                },
            });
            await onLoad();
        }
        catch (err) {
            setIsLoading(false);
            setError(API.getFriendlyMessage(err));
        }
    };
    useAsyncEffect(async () => {
        await onLoad();
    }, []);
    const isEditable = props.isEditable !== false;
    return (React.createElement(Card, { title: props.title, description: props.description, buttons: isEditable
            ? [
                {
                    title: "Edit Fields",
                    buttonStyle: ButtonStyleType.NORMAL,
                    onClick: () => {
                        setShowModelForm(true);
                    },
                    icon: IconProp.Edit,
                },
            ]
            : [] },
        React.createElement("div", { className: "border-t border-gray-200 px-4 py-5 sm:px-6 -m-6 -mt-2" },
            isLoading && !error && React.createElement(ComponentLoader, null),
            !isLoading && !error && schemaList.length === 0 && (React.createElement(ErrorMessage, { message: "No custom fields have been added for this resource. You may add custom fields in Project Settings." })),
            error && React.createElement(ErrorMessage, { message: error }),
            !model && React.createElement(ErrorMessage, { message: "Item not found" }),
            !isLoading && !error && model && (React.createElement(Detail, { id: props.name, item: model["customFields"] || {}, fields: schemaList.map((schemaItem) => {
                    const isDropdown = schemaItem.customFieldType ===
                        CustomFieldType.Dropdown ||
                        schemaItem.customFieldType ===
                            CustomFieldType.MultiSelectDropdown;
                    return {
                        key: schemaItem.name,
                        title: schemaItem.name,
                        description: schemaItem.description,
                        fieldType: schemaItem.customFieldType,
                        placeholder: "No data entered",
                        dropdownOptions: isDropdown
                            ? parseDropdownOptions(schemaItem.dropdownOptions)
                            : undefined,
                    };
                }), showDetailsInNumberOfColumns: 1 })),
            showModelForm && (React.createElement(BasicFormModal, { title: "Edit " + new props.modelType().singularName, onClose: () => {
                    return setShowModelForm(false);
                }, onSubmit: async (data) => {
                    await onSave(data).catch();
                }, formProps: {
                    initialValues: model["customFields"] || {},
                    fields: schemaList.map((schemaItem) => {
                        const isDropdown = schemaItem.customFieldType ===
                            CustomFieldType.Dropdown ||
                            schemaItem.customFieldType ===
                                CustomFieldType.MultiSelectDropdown;
                        return {
                            field: {
                                [schemaItem.name]: true,
                            },
                            title: schemaItem.name,
                            description: schemaItem.description,
                            fieldType: schemaItem.customFieldType,
                            required: false,
                            placeholder: "",
                            dropdownOptions: isDropdown
                                ? parseDropdownOptions(schemaItem.dropdownOptions)
                                : undefined,
                        };
                    }),
                } })))));
};
export default CustomFieldsDetail;
//# sourceMappingURL=CustomFieldsDetail.js.map