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

export const UserPrompt = () => {
   const context = useContext(ModalContext)!;
   const [prompt, setPrompt] = useState(context.initPrompt);
   const { generateNew } = useSendPrompt();
   const submit = () => {
      generateNew(prompt);
   };

   useEffect(() => {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      if(prompt && prompt.length > 0) {
         submit();
      } else {
         context.updateState({ editMode: !context?.editMode })
      }
   }, []);

   return (
      <div>
         {context.editMode && (
            <div className={'wpj-form-group'}>
               <div className="row wpj-form-group">
                  <div className="wpj-form-group-flex">
                     <div className="col-md-12">
                        <label>Zadání</label>
                        <textarea
                           name="data[user_text]"
                           className="input-sm form-control resize-vertical"
                           rows={6}
                           defaultValue={prompt}
                           onKeyUp={(e) => {
                              onKeyboardShiftEnter(e, () => submit());
                              onKeyboardEscape(e, () => context.updateState({ editMode: false }));
                           }}
                           onKeyDown={onKeyboardShiftEnter}
                           onChange={(e) => setPrompt(e.target.value)}
                        />
                     </div>
                  </div>
               </div>

               <div className="d-flex gap-1">
                  <button
                     className={`btn btn-info`}
                     disabled={context.loadingResponse}
                     onClick={submit}>
                     <i className="bi bi-stars m-r-1"></i>Použít zadání
                  </button>
               </div>
            </div>
         )}
      </div>
   );
};
