import {useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {UpdateDatasetEntry} from "../../../../../../../../../rest/dataset-entries";
import {handleError, handleSuccess} from "../../../../../../../../../helpers/notifications";
import Details from "../../details";

export default function DatasetEntryDetails({row, rowIndex, show, updated, notifications, fullWidth}) {
    const [loading, setLoading] = useState(0);
    const [saving, setSaving] = useState(false);
    const [datasetEntry, setDatasetEntry] = useState({
        entry: {
            messages: [
                {
                    input: row?.entry?.messages[0]?.input || "",
                    output: row?.entry?.messages[0]?.output || ""
                }
            ]
        },
        system: row?.entry?.system || "",
    });

    const saveDisabled = loading > 0 || saving;

    /**
     * Save
     *
     * @return {Promise<void>}
     */
    const save = async () => {
        setSaving(true);
        try {
            const res = await UpdateDatasetEntry(LimbChatbot.rest.url, LimbChatbot.rest.nonce, row.id, {
                entry: datasetEntry.entry
            });
            if (res?.id) {
                setDatasetEntry(prevState => ({
                    ...prevState,
                    entry: res.entry
                }));
                handleSuccess(notifications.set, {
                    title: __("Data saved successfully.", 'limb-chatbot'),
                });
                typeof updated === 'function' && updated(res.entry, row.id);
            } else {
                handleError(false, notifications.set, {
                    title: __("Failed to save changes.", 'limb-chatbot'),
                    description: __("Something went wrong.", 'limb-chatbot'),
                });
            }
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to save changes.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please try again.", 'limb-chatbot'),
            });
        }
        setSaving(false);
    }

    /**
     * Update dataset entry value
     *
     * @param {string} value Value
     * @param {string} key Key
     */
    const updateDatasetEntryValue = (value, key) => {
        setDatasetEntry(prevState => ({
            ...prevState,
            entry: {
                ...prevState.entry,
                messages: [
                    {
                        ...prevState.entry.messages[0],
                        [key]: value
                    }
                ]
            },
        }));
    }

    return <Details
        key={row.id}
        show={show}
        question={datasetEntry.entry.messages[0].input}
        setQuestion={(value) => updateDatasetEntryValue(value, 'input')}
        answer={datasetEntry.entry.messages[0].output}
        setAnswer={(value) => updateDatasetEntryValue(value, 'output')}
        saving={saving}
        saveDisabled={saveDisabled}
        save={save}
        notifications={notifications}
        fullWidth={fullWidth}
    />
}