import React, { useContext, useEffect, useRef } from 'react';
import { ModalContext } from '../context/ModalContext';
import '../styles.scss';
import { getCurrentResponse } from '../common/textUtil';

export const LlmAnswer = () => {
   const context = useContext(ModalContext)!;
   const scrollRef = useRef<HTMLDivElement>(null);

   const currentResponseAnswer =
      getCurrentResponse(context.responses, context.showResponseIndex)?.answer ?? '';

   useEffect(() => {
      if (scrollRef.current) {
         scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
      }
   }, [currentResponseAnswer]);

   const actionUndo = () => {
      context.updateState({
         showResponseIndex: Math.max(context.showResponseIndex - 1, 0),
      });
   };
   const actionRedo = () => {
      context.updateState({
         showResponseIndex: Math.min(context.showResponseIndex + 1, context.responses.length - 1),
      });
   };

   const renderButtons = () => {
      if (context.responses.length > 1) {
         return (
            <div className="pager">
               <ul className="pagination m-t-0 m-b-0">
                  <li>
                     <a onClick={actionUndo}>&laquo;</a>
                  </li>
                  <li className="unactive">
                     <a>
                        {context.showResponseIndex + 1} / {context.responses.length}
                     </a>
                  </li>
                  <li>
                     <a onClick={actionRedo}>&raquo;</a>
                  </li>
               </ul>
            </div>
         );
      }

      return <></>;
   };

   return (
      <>
         <div className="wpj-form-group">
            <label>Odpověď</label>
            <div
               className={'form-control scrollable-div'}
               ref={scrollRef}
               dangerouslySetInnerHTML={{
                  __html: currentResponseAnswer,
               }}></div>
         </div>
         {renderButtons()}
      </>
   );
};
