import React, { useEffect, useRef, useState } from "react";
import { Button, Modal, message } from "antd";
import io from "socket.io-client";
import { HiArrowDownCircle } from "react-icons/hi2";
import Cookies from "js-cookie";
import axios from "axios";
import { LoadingOutlined } from "@ant-design/icons";
import { Spin } from "antd";
// import { FaCheckDouble } from "react-icons/fa";

interface ChatScreenProps {
  isOpen: boolean;
  onClose: () => void;
  room: string;
  sender: string;
  reciever: string;
  name: string;
}

const ChatScreen: React.FC<ChatScreenProps> = ({
  isOpen,
  onClose,
  room,
  sender,
  reciever,
  name,
}) => {
  console.log("IS-OPEN", isOpen);
  console.log("chat info : ", room, sender, reciever);

  const [socket, setsocket] = useState<any>();

  const [messages, setMessages] = useState<any[]>([]);
  const [message, setMessage] = useState("");

  const [currentPage, setCurrentPage] = useState(1);
  const [loadingOldChats, setLoadingOldChats] = useState(false);
  const [fetchedAllChats, setfetchedAllChats] = useState(false);

  const [loader, setLoader] = useState(false);

  useEffect(() => {
    if (isOpen === true) {
      try {
        const newSocket = io("https://api.jazzagain.com/", {
          query: { room, sender, reciever },
          path: "/node/socket.io",
        });
        setsocket(newSocket);
      } catch (error) {
        console.error("Socket connection error:", error);
        // Handle the error (e.g., show an error message)
      }
    }

    return () => {
      socket?.disconnect();
    };
  }, [isOpen, room, sender, reciever]);

  useEffect(() => {
    if (socket && isOpen) {
      socket.on("chat-message", (msg: any) => {
        console.log("messages --> ", msg);
        socket.emit("message-seen", msg.messageId);

        // Add createdAt field with current timestamp to the message
        const newMsg = {
          ...msg,
          createdAt: new Date().toISOString(),
        };

        // Append new message to the end of the array
        setMessages((messages) => [...messages, newMsg]);
      });

      socket.on("join-room", (user: any) => {
        console.log("ROOM JOINED BY : ", user);
      });
    }

    return () => {};
  }, [socket, isOpen]);

  const chatContainerRef = useRef<any>(null);

  const handleScroll = () => {
    const container = chatContainerRef.current;
    if (
      container &&
      container.scrollTop === 0 &&
      !loadingOldChats &&
      !fetchedAllChats
    ) {
      setLoadingOldChats(true);
      const nextPage = currentPage + 1;
      fetchMessages(nextPage)
        .then((newMessages) => {
          if (newMessages.length > 0) {
            appendMessages(newMessages);
            setCurrentPage(nextPage);
          } else {
            setfetchedAllChats(true);
          }
        })
        .finally(() => setLoadingOldChats(false));
    }
  };

  useEffect(() => {
    chatContainerRef.current?.addEventListener("scroll", handleScroll);
    return () => {
      chatContainerRef.current?.removeEventListener("scroll", handleScroll);
    };
  }, [currentPage, loadingOldChats]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    getOldChats();
  }, []);

  // Function to append messages to the state
  // Function to append messages to the state
  const appendMessages = (newMessages: any) => {
    setMessages((prevMessages) => {
      return [...newMessages.reverse(), ...prevMessages];
    });
  };

  // Function to check if two dates are the same
  const isSameDate = (date1: string, date2: string) => {
    return (
      new Date(date1).toLocaleDateString() ===
      new Date(date2).toLocaleDateString()
    );
  };

  const getOldChats = () => {
    setLoader(true);
    const authToken = Cookies.get("jazz_token");
    const config = {
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    };
    axios
      .get(
        `https://api.jazzagain.com/node/chat/messages/${room}?page=1`,
        config
      )
      .then((res: any) => {
        console.log("res.data 133", res.data);
        const fetchedMessages = res.data.messages;

        // If there are existing messages, concatenate them in the correct order
        if (messages.length > 0) {
          setMessages((prevMessages) => [
            ...prevMessages,
            ...fetchedMessages.reverse(),
          ]);
        } else {
          // If there are no existing messages, simply set the fetched messages
          setMessages(fetchedMessages.reverse());
        }

        setLoader(false);
      });
  };

  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      (chatContainerRef.current as HTMLElement).scrollTo({
        top: chatContainerRef.current.scrollHeight,
        behavior: "smooth",
      });
    }
  };

  const handleScrollToBottom = () => {
    scrollToBottom();
  };

  const handleSendMessage = async () => {
    if (message.trim()) {
      socket.emit("chat-message", message);
      console.log("Sending message:", {
        message,
        sender,
        reciever,
        createdAt: new Date().toISOString(),
      });
      // Prepend new message to the beginning of the array
      setMessages((msg) => {
        console.log("Existing messages:", msg);
        return [
          ...msg,
          { message, sender, reciever, createdAt: new Date().toISOString() },
        ];
      });
      setMessage("");
      const authToken = Cookies.get("jazz_token");
      const body = {
        userId: reciever,
        title: "New message received (1)",
        body: message,
        data: {
          type: "chat",
          room: room,
        },
      };

      console.log(body);
      const axiosInstance = axios.create({
        baseURL: "https://api.jazzagain.com/node",
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });
      const notificationResponse = await axiosInstance.post(
        "/notification-token/send-notification",
        body
      );
      console.log("NOTI====", notificationResponse);
    }
  };

  // Function to fetch messages from the API
  const fetchMessages = async (page: any) => {
    const authToken = Cookies.get("jazz_token");
    const config = {
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    };
    const apiUrl = `https://api.jazzagain.com/node/chat/messages/${room}?page=${page}`;
    try {
      const response = await fetch(apiUrl, config);
      if (response.ok) {
        const data = await response.json();
        console.log("178", data.messages);
        return data.messages;
      } else {
        console.error("Failed to fetch messages");
        return [];
      }
    } catch (error) {
      console.error("Error while fetching messages:", error);
      return [];
    }
  };

  return (
    <>
      <Modal
        centered={true}
        title={name}
        open={isOpen}
        onCancel={onClose}
        maskStyle={{ background: "gray", opacity: 0.7 }}
        footer={null}
      >
        {/* <div className="w-full h-[500px] flex justify-center items-center bg-gray-100"> */}
        <div className="bg-white rounded-lg p-4 w-[100%]">
          {/* <div className="mb-4">
              <h2 className="text-md font-semibold">Chat started here</h2>
            </div> */}
          {loadingOldChats && (
            <div className="text-center text-gray-500">Loading...</div>
          )}
          {loader === true && (
            <div className="m-auto">
              <Spin
                indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
              />
            </div>
          )}

          <div className="h-60 overflow-y-auto mb-4" ref={chatContainerRef}>
            {messages.map((msg, index) => (
              <React.Fragment key={index}>
                {/* Conditionally render date and day of week for the first message */}
                {index === 0 && (
                  <div className="text-center text-gray-500 mb-2">
                    {/* Format the createdAt date to display date and day of week */}
                    {new Date(msg.createdAt).toLocaleDateString("en-US", {
                      weekday: "long", // "Monday"
                      year: "numeric", // "2021"
                      month: "long", // "July"
                      day: "numeric", // "19"
                    })}
                  </div>
                )}
                {/* Previous condition to display date if different from the previous message */}
                {index > 0 &&
                  !isSameDate(messages[index - 1].createdAt, msg.createdAt) && (
                    <div className="text-center text-gray-500 mb-2">
                      {new Date(msg.createdAt).toLocaleDateString() || ""}
                    </div>
                  )}
                <div
                  className={`${
                    msg.sender === sender ? "mb-2 text-right" : "mb-2 text-left"
                  }`}
                >
                  <div
                    className={`p-2 rounded-lg m-2 w-[50%] inline-block ${
                      msg.sender === sender ? "bg-blue-200" : "bg-orange-200"
                    }`}
                  >
                    {msg.message}
                  </div>
                  <sub className="text-gray-400 ml-1">
                    {new Date(msg.createdAt).toLocaleTimeString([], {
                      hour: "numeric",
                      minute: "2-digit",
                    })}
                    {msg.sender === sender && msg.seen && " seen"}
                  </sub>
                </div>
              </React.Fragment>
            ))}
          </div>

          <div className="mt-2 text-right">
            <button
              onClick={handleScrollToBottom}
              // className="bg-blue-500 text-white p-0 mb-1 rounded-[50%] w-[20px]"
            >
              <HiArrowDownCircle style={{ height: 30, width: 30 }} />
            </button>
          </div>
          <div className="flex">
            <input
              type="text"
              placeholder="Type your message..."
              className="flex-1 rounded-l-lg p-2 focus:outline-none"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />
            <button
              className="bg-blue-500 text-white p-2 rounded-r-lg"
              onClick={() => handleSendMessage()}
            >
              Send
            </button>
          </div>
        </div>
        {/* </div> */}
      </Modal>
    </>
  );
};

export default ChatScreen;
