import { useState } from 'react';
import PropTypes from 'prop-types';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import Button from '../../shared/components/_V2/Button';
import { useChatStore } from '../../state/stores/useChatStore';

const PromptBoxModal = ({ onSubmit }) => {
  const [promptMessage, setPromptMessage] = useState('');
  const [latestMessage, setLatestMessage] = useState({ user: '', response: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const { sendChatRequest } = useChatStore();

  const handleFormSubmit = async (event) => {
    event.preventDefault();
    if (promptMessage.trim()) {
      const requestData = {
        keywords: ['example', 'test'],
        data: promptMessage,
      };
      
      setLatestMessage({ user: promptMessage, response: '' });
      
      try {
        const result = await sendChatRequest('/chat/completions', requestData);
        const responseText = result.responseText || 'No response from server';
        setLatestMessage({ user: promptMessage, response: responseText });
        setIsModalOpen(true);
      } catch (error) {
        console.error('API request failed:', error);
        setLatestMessage({ user: promptMessage, response: 'Error communicating with server' });
        setIsModalOpen(true);
      }
      
      onSubmit(requestData);
      setPromptMessage('');
    }
  };

  return (
    <div className='flex items-center w-full h-full p-2 bg-gray-800'>
      <form onSubmit={handleFormSubmit} className='flex items-center w-full space-x-2'>
        <InputText
          type='text'
          value={promptMessage}
          onChange={(e) => setPromptMessage(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleFormSubmit(e);
            }
          }}
          className='flex-grow p-2 text-black rounded'
          placeholder='Enter your message...'
        />
        <Button label='Send' type='submit' className='p-2' />
      </form>

      {/* Modal for Latest Question & Response */}
      <Dialog
        visible={isModalOpen}
        onHide={() => setIsModalOpen(false)}
        header='Chat Response'
        className='w-[400px] p-4 bg-white rounded-lg shadow-lg'
        modal
      >
        <div className='space-y-2'>
          <div className='p-2 text-white bg-blue-500 rounded-lg'>
            <strong>You:</strong> {latestMessage.user}
          </div>
          <div className='p-2 text-white bg-gray-700 rounded-lg'>
            <strong>Assistant:</strong> {latestMessage.response}
          </div>
        </div>
        <Button label='Close' onClick={() => setIsModalOpen(false)} className='mt-3' />
      </Dialog>
    </div>
  );
};

PromptBoxModal.propTypes = {
  onSubmit: PropTypes.func.isRequired,
};

export default PromptBoxModal;
