import { useEffect, useRef, useState } from 'react';
import './App.css'
import { sendChatMessage } from './util/chat';


const BASE_URL='http://localhost:3333';

function App() {
  
  const [history, setHistory] = useState([]);
  const [processing, setProcessing] = useState(false);
  const [prompt, setPrompt] = useState([]);
  
  const refHistoryContainer= useRef(null);
  const refPrompContainer= useRef(null);

  function onSubmitToNode(event) {
    event.preventDefault();
    const input = event.target.elements.input.value;
    console.log("Submitted:", input);
    
    // setProcessing(true);


    fetch(`${BASE_URL}/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        input:[
          ...history,
          {
            role:'user',
            content:[{
              type:'input_text',
              text: input 
            }]
          }
        ]
      }),
    }).then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      response.json().then(data => {;
        console.log(data);

        // add to history
        setHistory(prev => [...prev, {
          role: 'user',
          content: [{
              type:'input_text',
              text: input
          }]
        }, {
          role: 'assistant',
          content: [{
              type:'output_text',
              text: data.output_text
          }]
        }]);              

        setPrompt([
          ...prompt,
          data.prompt,
        ]);

        // clear input
        event.target.elements.input.value = '';
        setProcessing(false);        

      });

    });


  }

  function onSubmit(event) {
    event.preventDefault();
    const input = event.target.elements.input.value;
    console.log("Submitted:", input);
    
    // setProcessing(true);


    sendChatMessage([
        ...history,
        {
          role:'user',
          content: input,
        }
    ]).then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      
      let data=response;
      console.log(data);

      // add to history
      setHistory(prev => [...prev, {
        role: 'user',
        content:input,
      }, {
        role: 'assistant',
        content: data.output_text,
      }]);              

      setPrompt([
        ...prompt,
        data.prompt,
      ]);

      // clear input
      event.target.elements.input.value = '';
      setProcessing(false);        

    });


  }
  useEffect(()=>{    
    refHistoryContainer.current.scrollTop = refHistoryContainer.current.scrollHeight;    
  },[history]);
  useEffect(()=>{    
    refPrompContainer.current.scrollTop = refPrompContainer.current.scrollHeight;    
  },[prompt]);

  return (
    <main className='h-screen flex flex-col gap-8 justify-end p-8'>
      <div ref={refPrompContainer} className='flex-1 flex flex-col gap-2 border-4 overflow-y-auto'>        
        {prompt?.length==0 ? (
          <div className='p-2 border-b border-gray-200'>Promp will appear here...</div>
        ):(
          prompt?.map((item, index) => (
            <div key={index} className='p-2 border-b border-gray-500 bg-pink-200'>
              <p className='text-lg'>{item}</p>
            </div>
          ))
        )}
      </div>      
      <div ref={refHistoryContainer} className='flex-1 overflow-y-auto'>
        <div className='flex flex-col justify-end gap-2'>
          {history?.length==0? (
            <div className='p-2'>History will appear here...</div>
          ):(
            history.map((item, index) => (
              <div key={index} className={`p-2 rounded border-4 ${item.role === 'user' ? 'bg-gray-100' : 'bg-yellow-100'}`}>
                <p className='text-lg whitespace-pre-wrap'>{item.content}</p>                
              </div>
            ))
          )}
        </div>
      </div>      
      <div className=''>
        <form className='flex flex-col justify-center *:border-4 gap-4' onSubmit={onSubmit} autoComplete="off">
          <input id="input" name="input" required className='self-stretch p-2' autoComplete="off"/>
          <button type="submit" className='rounded-full uppercase' disabled={processing}>Send</button>
        </form>
      </div>
    </main>
  )
}

export default App
