import {createPortal, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {handleError} from "../../../../helpers/notifications";
import {safeJsonParse} from "../../../../../helpers";
import Textarea from "../../../fields/textarea";

export default function AddFunction({added, close, notifications}) {
    // Actions state
    const [saving, setSaving] = useState(false);
    // Data
    const [data, setData] = useState('');

    /**
     * Validate
     *
     * @return {object|false}
     */
    const validateFunction = () => {
        const functionDef = data.trim();
        const obj = safeJsonParse(functionDef);
        // Check name
        if (!obj?.name) {
            if (functionDef.length) {
                handleError({message: "Invalid function definition."}, notifications.set, {
                    title: __("Attention", 'limb-chatbot'),
                    description: __("Invalid JSON provided.", 'limb-chatbot'),
                });
            }
            return false;
        }
        return obj;
    }

    /**
     * Save
     *
     * @return {Promise<void>}
     */
    const save = async () => {
        const validated = validateFunction();
        if (validated) {
            setSaving(true);
            // Add files
            const res = await added(validated);
            setSaving(false);
            // Close if done
            if (res) {
                close();
            }
        }
    }

    return createPortal(<div className='lbaic-settings-popup-layout'>
        <div className='lbaic-settings-popup-overlay' onClick={close}/>
        <div className='lbaic-settings-popup'>
            <div className='lbaic-settings-e-af-popup'>
                <div className='lbaic-settings-e-af'>
                    <div className='lbaic-settings-e-af-header'>
                        <div className='lbaic-settings-e-af-header-in'>
                            <h6 className='lbaic-settings-e-af-header-label'>{__("Add real time helpers", 'limb-chatbot')}</h6>
                            <p className='lbaic-settings-e-af-header-desc'>{__("The model will intelligently decided to call functions based on input it receives from the user.", 'limb-chatbot')}</p>
                        </div>
                        <div className='lbaic-settings-divider'/>
                    </div>
                    <div className='lbaic-settings-e-af-body'>
                        <div className='lbaic-settings-e-af-body-in'>
                            <Textarea value={data} setValue={setData} placeholder={`{
  "name": "get_stock_price",
  "description": "Get the current stock price",
  "strict": true,
  "parameters": {
    "type": "object",
    "properties": {
      "symbol": {
        "type": "string",
        "description": "The stock symbol"
      }
    },
    "additionalProperties": false,
    "required": [
      "symbol"
    ]
  }
}`}/>
                            <div className='lbaic-settings-e-af-body-desc'>
                                <p className='lbaic-settings-e-af-body-desc-in'>{__("Add “strict”: true to ensure the models response always follows the scheme", 'limb-chatbot')}</p>
                            </div>
                        </div>
                    </div>
                    <div className='lbaic-settings-e-af-footer'>
                        <button onClick={save}
                                className={`lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-primary${saving ? ' lbaic-settings-button-disabled' : ''}`}>
                            {saving &&
                                <svg className='lbaic-settings-button-i lbaic-settings-loading-circle lbaic-settings-button-loading-circle'
                                     xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>
                                    <use href='#lbaic-settings-circle'/>
                                </svg>}
                            <span className='lbaic-settings-button-label'>{__("Save", 'limb-chatbot')}</span>
                        </button>
                        <button className='lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-secondary'
                                onClick={close}>
                            <span className='lbaic-settings-button-label'>{__("Cancel", 'limb-chatbot')}</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>, document.getElementById('lbaic-settings-popup'))
}