import { useState } from 'react';
import Avatar from '../Avatar';
import { InputText } from 'primereact/inputtext';
import Button from '../../shared/components/_V2/Button';
import maleAvatar from '../../assets/male-avatar.png';
import femaleAvatar from '../../assets/female-avatar.png';
import { useChatStore } from '../../state/stores/useChatStore';

const PromptBoxModal = ({ response }) => {
  return response ? (
    <div className='absolute w-full p-2 mb-2 text-center text-white bg-gray-700 rounded bottom-full'>
      <strong>Assistant:</strong> {response}
    </div>
  ) : null;
};

const PromptBox = ({ onSubmit, activeRole }) => {
  const [input, setInput] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (input.trim()) {
      onSubmit(input);
      setInput('');
    }
  };

  return (
    <form
      onSubmit={handleSubmit}
      className='flex items-center w-full gap-4 p-4 bg-gray-500 rounded-lg shadow-md'
    >
      <div className='flex items-center flex-grow px-6 py-3 bg-white border border-gray-400 rounded-lg focus-within:ring-2 focus-within:ring-gray-500 h-14'>
        <InputText
          type='text'
          value={input}
          onChange={(e) => setInput(e.target.value)}
          className='w-full h-full text-black bg-transparent border-none focus:outline-none'
          placeholder={`Enter your message for ${activeRole}...`}
        />
      </div>
      <div className='flex h-14'>
        <Button
          label='Send'
          type='submit'
          className='px-6 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center justify-center h-full !m-0'
        />
      </div>
    </form>
  );
};

export default function AvatarPromptScreen() {
  const [responses, setResponses] = useState({ cfo: '', cpo: '' });
  const [activeRole, setActiveRole] = useState('CFO');
  const { sendChatRequest } = useChatStore();

  const handlePromptSubmit = async (message) => {
    console.log(`Prompt submitted for ${activeRole}:`, message);
    const requestData = { keywords: ['example', 'test'], data: message };
    try {
      const result = await sendChatRequest('/chat/completions', requestData);
      const responseText = result.responseText || 'No response from server';
      setResponses((prev) => ({
        ...prev,
        [activeRole.toLowerCase()]: responseText,
      }));
    } catch (error) {
      console.error('API request failed:', error);
      setResponses((prev) => ({
        ...prev,
        [activeRole.toLowerCase()]: 'Error communicating with server',
      }));
    }
  };

  return (
    <div className='flex flex-col justify-between w-screen h-screen bg-primary-light'>
      <div className='grid items-end flex-grow w-full grid-cols-6 pb-4'>
        {/* CFO (Column 2) */}
        <div className='relative flex flex-col items-center col-span-1 col-start-2'>
          <PromptBoxModal response={responses.cfo} />
          <div className='cursor-pointer' onClick={() => setActiveRole('CFO')}>
            <Avatar avatarUrl={maleAvatar} name='CFO' type='CFO' />
          </div>
        </div>

        {/* CPO (Column 5) */}
        <div className='relative flex flex-col items-center col-span-1 col-start-5'>
          <PromptBoxModal response={responses.cpo} />
          <div className='cursor-pointer' onClick={() => setActiveRole('CPO')}>
            <Avatar avatarUrl={femaleAvatar} name='CPO' type='CPO' />
          </div>
        </div>
      </div>

      {/* Full Width Input Box */}
      <div className='w-full p-4'>
        <PromptBox onSubmit={handlePromptSubmit} activeRole={activeRole} />
      </div>
    </div>
  );
}
