import React, { useContext, useEffect } from 'react';
import { ModalContext } from '../context/ModalContext';

export const PromptSelect = () => {
   const context = useContext(ModalContext);
   const changePrompt = (e: any) => {
      const newPrompt = context!.objectPrompts.find((val) => val.id == e.target.value)!;
      context?.updateState({ promptId: newPrompt.id, title: newPrompt.title });
   };

   useEffect(() => {
      (window as any).styleFormInputs('.llm-select');
   }, []);

   useEffect(() => {
      $('.llm-select .selecter').trigger('chosen:updated');
   });

   useEffect(() => {
      const $select = $('.llm-select');
      $select.on('change', changePrompt);
      return () => {
         $select.off('change', changePrompt);
      };
   }, [context?.objectPrompts]);

   return (
      <>
         <div className="flex-grow llm-select">
            <select
               className={'form-control selecter'}
               onChange={changePrompt}
               value={context?.promptId}
               disabled={context?.loading || context?.loadingResponse}>
               {context?.objectPrompts.map((value) => {
                  return (
                     <option key={value.id} value={value.id}>
                        {value.title}
                     </option>
                  );
               })}
            </select>
         </div>

         <div className="d-flex gap-1">
            <a
               title={'Otevřít nastavení promptu'}
               href={"javascript:nw('LlmPrompt', " + (context?.promptId ?? '') + ')'}
               className="btn btn-secondary">
               <span className="bi bi-gear m-r-1"></span>Nastavení
            </a>

            <button
               title={'Zobrazit zdroj promptu'}
               className={`btn btn-default`}
               onClick={() => context?.updateState({ editMode: !context?.editMode })}>
               <span className={'bi bi-file-earmark-code m-r-1'}></span>
               {!context?.editMode ? 'Zobrazit zdroj' : 'Skrýt zdroj'}
            </button>
         </div>
      </>
   );
};
