"use client";

import React, { useEffect, useRef, useState } from "react";
import { Outlet } from "react-router-dom";
import { FaSmile, FaPaperPlane } from "react-icons/fa";
import {
  message,
  conversation,
  sendMessage,
  messageCount,
  ticketNotification,
  readNotification,
  getTickets,
} from "../../../api/api";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../store";
import { toast } from "react-toastify";
import { formatDate } from "../../../common/DateFormant";
import Pusher from "pusher-js";
import EmojiPicker from "../../../components/bayerProfile/pages/components/EmojiPickerDynamic";
import Image from "next/image";
import Swal from "sweetalert2";

const Chat: React.FC = () => {
  const dispatch = useDispatch<any>();
  // 🔹 instead of only isChatVisible
  const [activeTab, setActiveTab] = useState<
    "messages" | "chat" | "notifications"
  >("messages");

  const [message2, setMessage] = useState("");
  const [recipientId, setRecipientId] = useState<string | null>(null);
  const [listingId, setListingId] = useState<string>();
  const chatContainerRef = useRef<HTMLDivElement | null>(null);

  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const messageData = useSelector((state: RootState) => state.MessageReducer);
  const connersaction = useSelector(
    (state: RootState) => state.ConversationReducer
  );

  const [conversationMessages, setConversationMessages] = useState<any>([]);
  const user = userData?.data?.user;
  const conversations = messageData.messageData?.data?.conversations;
  const [filteredConversations, setFilteredConversations] = useState<any>([]);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const emojiPickerRef = useRef<HTMLDivElement | null>(null);
  const { ticketsNotificationData } = useSelector(
    (state: RootState) => state.TicketsReducer
  );

  useEffect(() => {
    const messages = connersaction.messages?.data?.messages || [];
    setConversationMessages(messages);
  }, [connersaction]);

  useEffect(() => {
    const filtered = conversations
      ? Object.keys(conversations)
          .filter((convoId) => conversations[convoId]?.user?.id !== user?.id)
          .map((convoId) => conversations[convoId])
      : [];
    setFilteredConversations(filtered);
  }, [conversations, user?.id]);

  useEffect(() => {
    dispatch(message());
    dispatch(ticketNotification());
  }, [dispatch]);

  useEffect(() => {
    const appKey = process.env.NEXT_PUBLIC_PUSHER_APP_KEY || "";
    const cluster = process.env.NEXT_PUBLIC_PUSHER_APP_CLUSTER || "";

    let pusher = new Pusher(appKey, {
      cluster,
      forceTLS: true,
    });

    const subscribeToPusherEvents = () => {
      const channel = pusher.subscribe(`chat.${user?.id}`);
      channel.bind("App\\Events\\MessageSent", (data: any) => {
        const newMessage = data?.message;
        if (
          (newMessage.from_user_id === recipientId ||
            newMessage.to_user_id === recipientId) &&
          listingId
        ) {
          dispatch(conversation({ id: recipientId!, listingID: listingId }));

          setConversationMessages((prev: any) => {
            const messageExists = prev.some(
              (msg: any) => msg.id === newMessage.id
            );
            return messageExists ? prev : [...prev, newMessage];
          });
        }

        dispatch(messageCount());

        setFilteredConversations((prev: any) =>
          prev.map((convo: any) => {
            if (
              convo.user?.id === newMessage?.from_user_id ||
              convo.user?.id === newMessage?.to_user_id
            ) {
              const messageExists = convo.messages.some(
                (msg: any) => msg.id === newMessage.id
              );
              if (!messageExists) {
                return {
                  ...convo,
                  messages: [...convo.messages, newMessage],
                };
              }
            }
            return convo;
          })
        );

        if (newMessage.from_user_id !== user?.id) {
          toast.dismiss("new-message-toast");
          toast.info("New message received!", {
            toastId: "new-message-toast",
          });
        }
      });

      pusher.connection.bind("disconnected", () => {
        pusher.unsubscribe(`chat.${user?.id}`);
        pusher.disconnect();
        pusher = new Pusher(appKey, { cluster, forceTLS: true });
        subscribeToPusherEvents();
      });
    };

    subscribeToPusherEvents();

    return () => {
      pusher.unsubscribe(`chat.${user?.id}`);
      pusher.disconnect();
    };
  }, [dispatch, recipientId, listingId, user?.id]);

  const handleProfileClick = (userId: string, convoListingId: string) => {
    setRecipientId(userId);
    setListingId(convoListingId);
    dispatch(conversation({ id: userId, listingID: convoListingId }));
    setActiveTab("chat");
    dispatch(messageCount());
  };

  const handleSubmitMessage = () => {
    if (!recipientId) return toast.error("Recipient ID not found.");
    if (!listingId) return toast.error("Listing ID not found.");
    if (!message2.trim()) return toast.error("Message field is required.");

    const payload = {
      listing_id: listingId,
      to_user_id: recipientId,
      message: message2,
    };

    dispatch(sendMessage(payload))
      .then(() => {
        toast.success("Message sent!");
        setMessage("");
        dispatch(messageCount());
        dispatch(conversation({ id: recipientId!, listingID: listingId }));
      })
      .catch(() => {
        toast.error("Failed to send message.");
      });
  };

  const activeUser = filteredConversations.find(
    (convo: any) => convo?.user?.id === recipientId
  );

  const handleEmojiClick = (emojiObject: any) => {
    setMessage((prev) => prev + emojiObject.emoji);
    setShowEmojiPicker(false);
  };

  const handleMarkAllRead = () => {
    Swal.fire({
      title: "Mark all as read?",
      text: "Are you sure you want to mark all notifications as read?",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, mark all!",
      cancelButtonText: "Cancel",
    }).then((result) => {
      if (result.isConfirmed) {
        dispatch(readNotification())
          .unwrap()
          .then(() => {
            Swal.fire(
              "Done!",
              "All notifications marked as read (including ticket replies)",
              "success"
            );
            dispatch(ticketNotification()); // refresh notifications list
            dispatch(getTickets());
          })
          .catch(() => {
            Swal.fire(
              "Error",
              "Failed to mark notifications. Try again.",
              "error"
            );
          });
      }
    });
  };

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        emojiPickerRef.current &&
        !emojiPickerRef.current.contains(e.target as Node)
      ) {
        setShowEmojiPicker(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop =
        chatContainerRef.current.scrollHeight;
    }
  }, [conversationMessages]);

  return (
    <>
      <div className="md:w-full px-4 pt-4">
        {/* 🔹 Tab buttons */}
        <div className="flex gap-4 mb-4">
          <button
            onClick={() => setActiveTab("messages")}
            className={`px-4 py-2 rounded-md font-semibold ${
              activeTab === "messages"
                ? "bg-yellow-400 text-black"
                : "bg-gray-200 text-gray-700"
            }`}
          >
            All Messages
          </button>
          <button
            onClick={() => setActiveTab("notifications")}
            className={`relative px-4 py-2 rounded-md font-semibold ${
              activeTab === "notifications"
                ? "bg-yellow-400 text-black"
                : "bg-gray-200 text-gray-700"
            }`}
          >
            System Notifications
            {ticketsNotificationData?.data?.total_unread > 0 && (
              <span className="absolute -top-2 -right-2 bg-yellow-400 text-black text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center">
                {ticketsNotificationData.data.total_unread}
              </span>
            )}
          </button>
        </div>

        <div className="flex flex-col gap-4 md:flex-row mb-3">
          {/* 🔹 Messages Tab */}
          {activeTab === "messages" && (
            <div className="md:container mx-auto px-4">
              {filteredConversations.map((convo: any) => {
                const lastMessage = convo.messages[convo.messages.length - 1];
                const unreadCount = convo.messages.filter(
                  (msg: any) => !msg.read && msg.to_user_id === user?.id
                ).length;

                return (
                  <div key={convo.user?.id} className="w-full">
                    <div
                      className="flex items-center justify-start md:p-3 xs:p-2 bg-white rounded-lg hover:shadow-lg cursor-pointer md:w-[31rem]"
                      onClick={() =>
                        handleProfileClick(
                          convo.user?.id,
                          convo?.messages[0]?.listing_id
                        )
                      }
                    >
                      <Image
                        unoptimized
                        src={convo?.user?.profile_url || "/default-profile.png"}
                        alt="Profile"
                        width={70}
                        height={70}
                        className="rounded-full h-14 w-14 mr-4"
                      />
                      <div className="text-start">
                        <h2 className="font-bold md:text-xl xs:text-lg capitalize relative mb-1 text-black">
                          {convo.user.name}
                          {unreadCount > 0 && (
                            <span className="absolute top-0 right-0 bg-red-500 text-white text-xs font-bold rounded-full px-2 py-1">
                              {unreadCount}
                            </span>
                          )}
                        </h2>
                        {lastMessage && (
                          <>
                            <p className="text-gray-500 text-sm font-semibold capitalize">
                              {lastMessage.message.length > 5
                                ? `${lastMessage.message.slice(0, 17)}...`
                                : lastMessage.message}
                            </p>
                            <p className="text-gray-500 xs:text-sm md:text-sm">
                              Last seen {formatDate(lastMessage.updated_at)}
                            </p>
                          </>
                        )}
                      </div>
                    </div>
                    <hr className="border-b-1 border-gray-200 mt-4" />
                  </div>
                );
              })}
            </div>
          )}

          {/* 🔹 Notifications Tab */}
          {activeTab === "notifications" && (
            <div className="bg-white rounded-lg shadow-md p-6 w-full md:max-w-xl mx-auto">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-bold text-black">Notifications</h2>
                {ticketsNotificationData?.data?.notifications?.length ? (
                  <button
                    onClick={handleMarkAllRead}
                    className="text-sm text-blue-600 hover:underline"
                  >
                    Mark all as read
                  </button>
                ) : null}
              </div>

              <p className="text-gray-600 mb-4">Your latest notifications:</p>
              <ul className="space-y-2 max-h-[400px] overflow-y-auto">
                {ticketsNotificationData?.data?.notifications?.length ? (
                  [...ticketsNotificationData.data.notifications] // copy array
                    .sort((a: any, b: any) => a.is_read - b.is_read) // unread first
                    .map((notif: any) => (
                      <li
                        key={notif.id}
                        className={`px-4 py-3 rounded-md border ${
                          notif.is_read === 0
                            ? "bg-yellow-50 border-yellow-300" // unread
                            : "bg-gray-50 border-gray-200" // read
                        } text-black`}
                      >
                        <p className="font-medium">{notif.message}</p>
                        {notif.created_at && (
                          <span className="text-gray-400 text-xs mt-1 block">
                            {formatDate(notif.created_at)}
                          </span>
                        )}
                      </li>
                    ))
                ) : (
                  <li className="text-gray-500 text-center py-6">
                    No notifications available
                  </li>
                )}
              </ul>
            </div>
          )}

          {/* 🔹 Chat Tab */}
          {activeTab === "chat" && (
            <div className="w-full md:w-full">
              <div className="bg-white flex items-center border-b border-gray-200 p-4">
                <button
                  onClick={() => setActiveTab("messages")}
                  className="text-black hover:text-gray-800 mr-4 p-2"
                >
                  ←
                </button>
                <Image
                  unoptimized
                  src={activeUser?.user?.profile_url}
                  alt="User Avatar"
                  className="w-11 h-11 rounded-full"
                  width={44}
                  height={44}
                />
                <div className="ml-4">
                  <h2 className="md:text-2xl xs:text-lg text-black font-semibold capitalize">
                    {activeUser?.user?.name || "Chat"}
                  </h2>
                  <p className="md:text-lg xs:txt-sm text-black">
                    {activeUser?.messages.length
                      ? `Last message ${formatDate(
                          activeUser.messages[activeUser.messages.length - 1]
                            ?.updated_at
                        )}`
                      : "No recent messages"}
                  </p>
                </div>
              </div>

              <div
                ref={chatContainerRef}
                className="chat-container bg-gray-50 p-4 space-y-4 overflow-y-auto h-[350px] max-h-[350px] border-t border-b border-gray-200"
              >
                {conversationMessages.length ? (
                  conversationMessages.map((msg: any) => (
                    <div
                      key={msg.id}
                      className={`flex ${
                        msg.from_user_id === recipientId
                          ? "justify-start"
                          : "justify-end"
                      }`}
                    >
                      <div
                        className={`rounded-lg p-3 text-sm ${
                          msg.from_user_id === recipientId
                            ? "bg-blue-100 text-black"
                            : "bg-green-100 text-black"
                        } max-w-[70%]`}
                      >
                        <p className="text-start">{msg.message}</p>
                        <p className="text-xs text-black mt-1 text-end">
                          {formatDate(msg.updated_at)}
                        </p>
                      </div>
                    </div>
                  ))
                ) : (
                  <p className="text-center text-black">
                    No messages yet. Start the conversation!
                  </p>
                )}
              </div>

              <div className="flex items-center bg-white border-t border-gray-200 p-4 relative">
                <button
                  className="text-gray-600 hover:text-gray-800 relative p-1"
                  onClick={() => setShowEmojiPicker((prev) => !prev)}
                >
                  <FaSmile size={24} />
                </button>
                {showEmojiPicker && (
                  <div
                    ref={emojiPickerRef}
                    className="absolute top-20 md:left-4 xs:left-0 z-50 bg-white shadow-lg border rounded-md p-2"
                  >
                    <EmojiPicker
                      reactionsDefaultOpen={true}
                      width={window.innerWidth < 640 ? "20em" : "50em"}
                      onEmojiClick={handleEmojiClick}
                    />
                  </div>
                )}
                <input
                  type="text"
                  value={message2}
                  onChange={(e) => setMessage(e.target.value)}
                  placeholder="Type your message..."
                  onKeyDown={(e) => e.key === "Enter" && handleSubmitMessage()}
                  className="flex-grow text-black bg-gray-100 border-none focus:ring-2 focus:ring-blue-400 rounded-lg mx-2 px-3 py-2"
                />
                <button
                  onClick={handleSubmitMessage}
                  className="bg-blue-500 text-white rounded-full p-2 hover:bg-blue-600"
                >
                  <FaPaperPlane size={20} />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
      <div className="bg-gray-100 right_section">
        <Outlet />
      </div>
    </>
  );
};

export default Chat;
