import React, {useState, useRef, useEffect} from 'react'
import SenderMessage from '../components/senderMessage'
import ReceiverMessage from '../components/receiverMessage'
import io from 'socket.io-client';

export default function MessageBox({id, seller}) {
    const [message, setMessage] = useState("");
    const [messages, setMessages] = useState([]);
    const socketRef = useRef(null);
    const chatBoxRef = useRef(null);
  //  const {name} = (await auth()).user;
//console.log(searchParams)

    const buyerId = id;
   console.log(buyerId)

    const sellerId = seller
    console.log(seller)
   useEffect(() => {
    const fetchChatHistory = async () => {
      try {
        const response = await fetch(`https://cloud.247tranzact.com/api/chat/history?buyerId=${buyerId}&sellerId=${sellerId}`);
              console.log(response)
  const data = await response.json();
        setMessages(data);

       {/* const unreadMessages = data.filter(msg => !msg.read && msg.receiverId === buyerId);
        if (unreadMessages.length > 0) {
          markMessagesAsRead(unreadMessages.map(msg => msg.id));
        }
      */}} catch (error) {
        console.error("Error fetching chat history:", error);
      }
    };

    fetchChatHistory();

   { /*const markMessagesAsRead = async () => {
      try {
        const viewerId = userid;
        await fetch("http://localhost:7000/chat/markAsRead", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ buyerId, sellerId, viewerId }),
        });
      } catch (error) {
        console.error("Error marking messages as read:", error);
      }
    };
    markMessagesAsRead();
    const intervalId = setInterval(fetchChatHistory, 1000);
    return () => clearInterval(intervalId);*/}
  }, [buyerId, sellerId]);

    const handleSendMessage = () => {
        if (message.trim() && socketRef.current) {
          const newMessage = {
            senderId: buyerId,
            receiverId: sellerId,
            content: message,
            read: false,
          };
    console.log(newMessage)
          socketRef.current.emit("sendMessage", newMessage);
          setMessages((prevMessages) => [...prevMessages, newMessage]);
          setMessage("");
        }
      };
console.log(messages)
      
  useEffect(() => {
    if (!socketRef.current) {
      socketRef.current = io("https://cloud.247tranzact.com/");
      socketRef.current.emit("joinRoom", { buyerId, sellerId });

      socketRef.current.on("receiveMessage", (message) => {
        setMessages((prevMessages) => [...prevMessages, message]);
        if (message.receiverId === buyerId) {
          markMessagesAsRead([message.id]);
        }
      });
    }

    return () => {
      if (socketRef.current) {
        socketRef.current.disconnect();
        socketRef.current = null;
      }
    };
  }, [buyerId, sellerId]);
  return (
    <div className="flex flex-col flex-auto h-full p-6">
    <div
      className="flex flex-col flex-auto flex-shrink-0 rounded-2xl bg-gray-100 h-full p-4"
    >
      <div className="flex flex-col h-full overflow-x-auto mb-4" >
        <div className="flex flex-col h-full" ref={chatBoxRef}>

        {messages.map((msg, index) => (
          <div className="grid grid-cols-12 gap-y-2" key={index}>
            {msg.senderId===buyerId ? <SenderMessage content={msg.content}/>
           :<ReceiverMessage content={msg.content}/>}
            
       
          </div>
            ))
          }
        </div>
      </div>
      <div
        className="flex flex-row items-center h-16 rounded-xl bg-white w-full px-4"
      >
        <div>
          <button
            className="flex items-center justify-center text-gray-400 hover:text-gray-600"
          >
            <svg
              className="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
              ></path>
            </svg>
          </button>
        </div>
        <div className="flex-grow ml-4">
          <div className="relative w-full">
            <input
              type="text"
              className="flex w-full border rounded-xl focus:outline-none focus:border-indigo-300 pl-4 h-10"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Type your message..."
            />
            <button
              className="absolute flex items-center justify-center h-full w-12 right-0 top-0 text-gray-400 hover:text-gray-600"
               
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                ></path>
              </svg>
            </button>
          </div>
        </div>
        <div className="ml-4">
          <button
          onClick={handleSendMessage}
            className="flex items-center justify-center bg-indigo-500 hover:bg-indigo-600 rounded-xl text-white px-4 py-1 flex-shrink-0"
          >
            <span>Send</span>
            <span className="ml-2">
              <svg
                className="w-4 h-4 transform rotate-45 -mt-px"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
                ></path>
              </svg>
            </span>
          </button>
        </div>
      </div>
    </div>
  </div>
  )
}
