import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Send, MessageSquare } from "lucide-react";
import { Modal } from "@/components/ui/modal";
import {
  socketEventSendMessage,
  socketEventGetMessage,
  socketEventCreateConnection,
  socketEventCloseConnection,
  socketEventBookingUpdate,
  socketEventGetAllMessages,
  socketEventConnected,
  socketEventDisconnected,
} from "@/hooks/socketEvents";

import { io, Socket } from "socket.io-client";
import { API_ROOT } from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";

interface HelpButtonProps {
  orderStatus?: string;
  receiverId?: string;
  orderId?: string;
  receiverType?: "driver" | "customer" | "vendor";
}

const HelpButton: React.FC<HelpButtonProps> = ({ orderStatus, receiverId, orderId, receiverType = "driver" }) => {
  const [messages, setMessages] = useState<any[]>([]);
  const [messageInput, setMessageInput] = useState("");
  const [chatModal, setChatModal] = useState({ open: false, data: null });
  const [connectionId, setConnectionId] = useState<string | null>(null);
  const [socketConnect, setSocketConnect] = useState(false);
  const socketRef = useRef<Socket | null>(null);
  const messagesEndRef = useRef<HTMLDivElement | null>(null);

  const { userInfo } = useGlobalContext();
  const access_token = typeof window !== "undefined" && sessionStorage.getItem("token");

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const sendMessage = () => {
    if (!messageInput.trim() || !userInfo || !connectionId) return;

    socketRef.current?.emit(socketEventSendMessage, {
      message: messageInput,
      receiver_id: receiverId,
      receiver_type: receiverType,
      connection_id: connectionId,
      order_id: orderId,
    });

    setMessages((prev) => [...prev, { message: messageInput, isSelf: true }]);
    setMessageInput("");
    scrollToBottom();
  };

  const openChatModal = () => {
    if (!userInfo || !receiverId || !orderId) {
      console.error("Missing user, receiverId, or orderId.");
      return;
    }

    if (!socketRef.current?.connected) {
      console.warn("Socket not connected yet.");
      return;
    }

    const payload = {
      order_id: orderId,
      receiver_type: receiverType,
      receiver_id: receiverId,
    };

    // Emit socket event to create a connection
    socketRef.current.emit(socketEventCreateConnection, payload, (data: any) => {
      console.log("Connection response data:", data);
    });
  };

  useEffect(() => {
    if (!access_token) {
      setSocketConnect(false);
      return;
    }

    const token = sessionStorage.getItem("token");

    const socket = io(API_ROOT, {
      extraHeaders: {
        token: token || "",
        language: "en",
      },
      reconnection: true,
    });

    socketRef.current = socket;

    socket.on(socketEventConnected, () => {
      console.log("✅ Socket connected:", socket.id);
      setSocketConnect(true);
    });

    socket.on(socketEventDisconnected, () => {
      console.log("❌ Socket disconnected");
      setSocketConnect(false);
    });

    socket.on("exception", (error) => {
      console.error("Socket exception:", error);
    });

    socket.on("error", (err) => {
      console.error("Socket error:", err);
    });

    return () => {
      socket.disconnect();
      setSocketConnect(false);
    };
  }, [access_token, userInfo]);

  useEffect(() => {
    const token = sessionStorage.getItem("token");

    if (!token) return;

    const socket = socketRef.current;

    if (socket) {
      socket.on(socketEventGetAllMessages, (payload: any) => {
        console.log(payload, 'payload');
        const msgs = payload.data.map((msg: any) => ({
          message: msg.message,
          isSelf: msg.sent_id === userInfo?._id,
        }));
        setMessages(msgs);
        scrollToBottom();
      });

      socket.on(socketEventCreateConnection, (res: any) => {
        console.log("create-connection", res?.response);
        const connId = res?.response;
        if (connId) {
          setConnectionId(connId);
          socket.emit(socketEventGetAllMessages, {
            connection_id: connId,
            order_id: orderId,
          });
          setChatModal({ open: true, data: res });
        }
      });

      socket.on(socketEventBookingUpdate, (data: any) => {
        console.log("Booking updated:", data);
      });
    }

    return () => {
      if (socket) {
        socket.off(socketEventGetAllMessages);
        socket.off(socketEventCreateConnection);
        socket.off(socketEventBookingUpdate);
      }
    };
  }, [userInfo, orderId, socketConnect]);

  useEffect(() => {
    const handleIncomingMessage = (data: any) => {
      console.log("Incoming message:", data);

      const messageOrderId = data.order_id || data.orderId;
      if (messageOrderId && messageOrderId !== orderId) {
        return;
      }

      const messageSenderId = data.sent_id || data.senderId || data.sender_id || data.sent_by;

      if (messageSenderId === userInfo?._id) {
        // Skip own message because it was already added to local state in sendMessage
        return;
      }

      const newMessage = {
        message: data.message,
        isSelf: false, // Since sender is not current user, it is from the other party
      };

      setMessages((prev) => [...prev, newMessage]);
      scrollToBottom();
    };

    socketRef.current?.on(socketEventGetMessage, handleIncomingMessage);

    return () => {
      socketRef.current?.off(socketEventGetMessage, handleIncomingMessage);
    };
  }, [socketRef, userInfo, orderId, socketConnect]);


  return (
    <>
      <div className="max-w-md w-full mx-auto">
        <button
          className="flex items-center justify-between w-full p-4 rounded-xl bg-white shadow-sm border border-gray-100 hover:shadow-md transition-all duration-200"
          onClick={openChatModal}
        >
          <div className="flex items-center gap-3">
            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-cyan-100 flex items-center justify-center">
              <MessageSquare className="w-5 h-5 text-cyan-600" />
            </div>
            <div className="text-left">
              <p className="font-medium text-sm text-gray-800">Chat with Driver</p>
            </div>
          </div>
          <div className="flex-shrink-0">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5 text-gray-400"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
                clipRule="evenodd"
              />
            </svg>
          </div>
        </button>
      </div>

      <Modal
        title="Chat with Driver"
        description="Please share your concerns"
        isOpen={chatModal.open}
        onClose={() => {
          if (userInfo) {
            socketRef.current?.emit(socketEventCloseConnection, {
              user_id: userInfo._id,
              scope: 'customer',
            });
          }
          setChatModal({ open: false, data: null });
          setMessages([]);
          setConnectionId(null);
        }}
      >
        <div className="flex flex-col h-[510px] overflow-hidden">
          <div className="flex-1 overflow-y-auto px-4 py-2 space-y-3 bg-[#F9F9F9]">
            {messages.length === 0 ? (
              <div className="text-sm text-gray-500 text-center py-10">No messages yet. Start the conversation!</div>
            ) : (
              messages.map((msg, i) => (
                <div key={i} className={`flex ${msg.isSelf ? "justify-end" : "justify-start"}`}>
                  <div
                    className={`max-w-[75%] px-4 py-2 rounded-2xl shadow-sm text-sm ${msg.isSelf
                      ? "bg-primary text-white rounded-br-none"  // Sent message: Primary background
                      : "bg-[#F3F4F6] text-gray-800 rounded-bl-none" // Received message: Light grey background
                      }`}
                  >
                    {msg.message}
                  </div>
                </div>
              ))

            )}
            <div ref={messagesEndRef} />
          </div>
          <div className="flex justify-between items-center gap-2 px-4 py-3 border-t border-gray-200">
            <input
              className="flex-1 py-2 px-4 text-sm text-gray-700 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Type a message"
              value={messageInput}
              onChange={(e) => setMessageInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") sendMessage();
              }}
            />
            <Button className="w-12 h-12" onClick={sendMessage} aria-label="Send Message">
              <Send className="w-5 h-5" />
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default HelpButton;
