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

export default function DataSourceDetails({dataset, datasetIndex, show, notifications}) {
    const [loading, setLoading] = useState(0);
    const [saving, setSaving] = useState(false);
    const [datasetEntry, setDatasetEntry] = useState({
        entry: {
            messages: [
                {
                    input: "",
                    output: ""
                }
            ]
        },
        system: '',
    });

    const saveDisabled = loading > 0 || saving;

    useEffect(() => {
        if (show) {
            if (!datasetEntry?.id) {
                fetchData();
            }
        }
    }, [show]);

    const fetchData = async () => {
        setLoading(prev => prev + 1);
        try {
            const res = await GetDatasetEntries(LimbChatbot.rest.url, LimbChatbot.rest.nonce, dataset.id);
            if (res?.items?.length) {
                setDatasetEntry(res?.items[0]);
            }
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to get details data.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check and try again.", 'limb-chatbot'),
            });
        }
        setLoading(prev => prev - 1);
    }

    /**
     * Save
     *
     * @return {Promise<void>}
     */
    const save = async () => {
        setSaving(true);
        try {
            const res = await UpdateDatasetEntry(LimbChatbot.rest.url, LimbChatbot.rest.nonce, datasetEntry.dataset_id, {
                entry: datasetEntry.entry
            });
            if (res?.id) {
                setDatasetEntry(prevState => ({
                    ...prevState,
                    entry: res.entry
                }))
                handleSuccess(notifications.set, {
                    title: __("Data saved successfully.", 'limb-chatbot'),
                });
            } 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={dataset.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}
    />
}