import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../services/AuthContext';
import { useNavigate } from 'react-router-dom';

const processMessages = (messageObject) => {
  return (previousMessages) => {
    if (previousMessages.length > 0 && previousMessages[previousMessages.length - 1].sender === messageObject.sender) {
      const newMessage = {text:previousMessages[previousMessages.length - 1].text+ ' ' + messageObject.text, sender: messageObject.sender};
      return [...previousMessages.slice(0, -1), newMessage];
    } else {
      return [...previousMessages, messageObject];
    }
  }
}

const ChatApi = () => {
  const { token, logout } = useAuth();
  const navigate = useNavigate();
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');


  const sendMessage = (e) => {
    e.preventDefault();
    if (!input.trim()) return;

    const message = {
      type: 'message',
      content: input
    };

    setMessages(processMessages({
      text: input,
      sender: 'user'
    }));
    fetch('http://localhost:8000/api/message', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        message: input
      })
    }).then(response => response.json()).then(data => {
      setMessages(processMessages({
        text: data.message?.content,
        sender: 'ai'
      }));
    });
    setInput('');
  };

  // Rest of your component (file upload handler, UI rendering, etc.)
  return (
    <div className="flex flex-col bg-gray-100 h-[90vh]">
      {/* Messages area */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4" >
        {(messages || []).map((message, index) => (
          <div
            key={index}
            className={`p-3 rounded-lg max-w-[80%] ${message.sender === 'user'
                ? 'ml-auto bg-blue-500 text-white'
                : message.sender === 'ai'
                  ? 'bg-gray-200'
                  : 'bg-yellow-100 mx-auto'
              }`}
          >
            {message.text}
          </div>
        ))}
      </div>

      {/* Input area */}
      <div className="p-4 bg-white border-t">
        <form onSubmit={sendMessage} className="flex gap-4">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Type your message..."
            className="flex-1 p-2 border rounded"
          />
          <button
            type="submit"
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
          >
            Send
          </button>

          <button
            onClick={() => {
              logout();
              navigate('/login');
            }}
            className="px-4 py-2 text-white bg-red-500 rounded hover:bg-red-600"
          >
            Logout
          </button>
        </form>
      </div>
    </div>
  );
};

export default ChatApi;
