import React, { useContext, useState } from 'react';
import { ModalContext } from '../context/ModalContext';
import { useSendPrompt } from '../common/hooks/useSendPrompt';
import { onKeyboardEnter } from '../common/textUtil';

export const EditPrompt = () => {
   const context = useContext(ModalContext)!;
   const { editCurrent, retryCurrent, stopRequest } = useSendPrompt();
   const [editPrompt, setEditPrompt] = useState('');

   const submit = () => {
      if (context.loadingResponse) {
         stopRequest();
      } else if (editPrompt.trim().length) {
         editCurrent(editPrompt);
         setEditPrompt('');
      } else {
         retryCurrent();
      }
   };

   return (
      <>
         <div className="flex-grow">
            <label>Doplnit zadání</label>
            <input
               name="data[user_text]"
               className="input-sm form-control"
               value={editPrompt}
               onKeyUp={(e) => onKeyboardEnter(e, () => submit())}
               onChange={(e) => setEditPrompt(e.target.value)}></input>
         </div>

         <div>
            <button
               className={`btn btn-info ${context.loadingResponse ? ' is-submitting-icon' : ''}`}
               disabled={false}
               title={'Generovat'}
               onClick={submit}>
               <i className="bi bi-stars m-r-1"></i>
               {context.loadingResponse ? 'Zastavit' : 'Generovat'}
            </button>
         </div>
      </>
   );
};
