"use client";

import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { useSocket } from "@/context/SocketContext";
import { useAppSelector } from "@/store/hooks";
import { useRouter } from "next/navigation";
import AuthGuard from "@/components/auth/AuthGuard";
import axios from "axios";
import { Send, ArrowLeft, Search, MoreVertical, Phone, Video, Paperclip, X, Trash2, Smile, Menu } from "lucide-react";
import Link from "next/link";
import { Modal } from "@/components/common/modal";
import { toast } from "react-toastify";
import EmojiPicker from 'emoji-picker-react';

const ChatAvatar = ({ user, className = "h-10 w-10", textSize = "text-base" }: { user: any, className?: string, textSize?: string }) => {
  const [imgError, setImgError] = useState(false);

  if (!user) return null;

  if (user.avatarUrl && !imgError) {
    return (
      <div className={`relative shrink-0 ${className}`}>
        {/* <Image
          src={user.avatarUrl}
          alt={user.firstName || 'User'}
          fill
          className="rounded-full object-cover border border-gray-200"
          onError={() => setImgError(true)}
        /> */}
      </div>
    );
  }

  return (
    <div className={`relative shrink-0 flex items-center justify-center rounded-full bg-[#112546] text-gray-200 font-semibold ${className} ${textSize}`}>
      {user?.firstName?.charAt(0).toUpperCase() || 'U'}
    </div>
  );
};

interface ChatUser {
  id: string;
  firstName: string;
  lastName: string;
  avatarUrl: string;
  email: string;
  unreadCount?: number;
}

interface ChatMessage {
  id: string;
  senderId: string;
  receiverId: string;
  content: string | null;
  attachmentUrl?: string | null;
  attachmentType?: string | null;
  attachmentName?: string | null;
  isRead: boolean;
  createdAt: string;
}

export default function ChatPage() {
  const router = useRouter();
  const { socket, onlineUsers } = useSocket();
  const currentUser = useAppSelector((state) => state.auth.user);

  const [users, setUsers] = useState<ChatUser[]>([]);
  const [selectedUser, setSelectedUser] = useState<ChatUser | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputText, setInputText] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);

  const messagesEndRef = useRef<HTMLDivElement>(null);

  const [showMobileSidebar, setShowMobileSidebar] = useState(false);
  const [currentTime, setCurrentTime] = useState(Date.now());

  useEffect(() => {
    const interval = setInterval(() => setCurrentTime(Date.now()), 60000);
    return () => clearInterval(interval);
  }, []);

  const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000";

  // Fetch users
  useEffect(() => {
    const token = localStorage.getItem("token") || sessionStorage.getItem("token");
    if (!token) return;

    const fetchUsers = async () => {
      try {
        const response = await axios.get(`${apiUrl}/api/chat/users`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (response.data.success) {
          setUsers(response.data.data);
        }
      } catch (error) {
        console.error("Error fetching chat users:", error);
      }
    };

    fetchUsers();
  }, [apiUrl]);

  // Fetch messages when a user is selected
  useEffect(() => {
    const token = localStorage.getItem("token") || sessionStorage.getItem("token");
    if (!selectedUser || !token) return;

    const fetchMessages = async () => {
      setIsLoading(true);
      try {
        const response = await axios.get(`${apiUrl}/api/chat/messages/${selectedUser.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (response.data.success) {
          setMessages(response.data.data);
          scrollToBottom();

          // Mark as read in backend
          try {
            await axios.put(`${apiUrl}/api/chat/messages/${selectedUser.id}/read`, {}, {
              headers: { Authorization: `Bearer ${token}` }
            });
            // Clear unread count locally
            setUsers(prev => prev.map(u => u.id === selectedUser.id ? { ...u, unreadCount: 0 } : u));
            window.dispatchEvent(new CustomEvent('chat_read'));
          } catch (err) {
            console.error("Error marking messages as read", err);
          }
        }
      } catch (error) {
        console.error("Error fetching messages:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMessages();
  }, [selectedUser, apiUrl]);

  // Socket event listeners for messages
  useEffect(() => {
    if (!socket) return;

    const handleMessageSent = (message: ChatMessage) => {
      if (selectedUser && message.receiverId === selectedUser.id) {
        setMessages((prev) => [...prev, message]);
        scrollToBottom();
      }

      // Move receiver to top
      setUsers(prevUsers => {
        const receiverId = message.receiverId;
        const existingUser = prevUsers.find(u => u.id === receiverId);
        if (!existingUser) return prevUsers;
        return [existingUser, ...prevUsers.filter(u => u.id !== receiverId)];
      });
    };

    const handleReceiveMessage = async (message: ChatMessage) => {
      // Show notification sound/toast here in future

      if (selectedUser && (message.senderId === selectedUser.id || message.receiverId === selectedUser.id)) {
        setMessages((prev) => [...prev, message]);
        scrollToBottom();

        // If it's from the currently selected user, mark as read immediately
        if (message.senderId === selectedUser.id) {
          try {
            const token = localStorage.getItem("token") || sessionStorage.getItem("token");
            await axios.put(`${apiUrl}/api/chat/messages/${selectedUser.id}/read`, {}, {
              headers: { Authorization: `Bearer ${token}` }
            });
            window.dispatchEvent(new CustomEvent('chat_read'));
          } catch (err) { }
        }
      } else {
        // Increment unread count for the sender
        setUsers(prevUsers => prevUsers.map(u =>
          u.id === message.senderId
            ? { ...u, unreadCount: (u.unreadCount || 0) + 1 }
            : u
        ));
      }

      // Move sender/receiver to top
      setUsers(prevUsers => {
        const otherUserId = message.senderId === currentUser?.id ? message.receiverId : message.senderId;
        const existingUser = prevUsers.find(u => u.id === otherUserId);
        if (!existingUser) return prevUsers;
        return [existingUser, ...prevUsers.filter(u => u.id !== otherUserId)];
      });
    };

    const handleMessageRead = ({ readBy }: { readBy: string }) => {
      if (selectedUser && readBy === selectedUser.id) {
        setMessages(prev => prev.map(msg => 
          msg.senderId === currentUser?.id && !msg.isRead 
            ? { ...msg, isRead: true } 
            : msg
        ));
      }
    };

    const handleMessageDeleted = ({ messageId }: { messageId: string }) => {
      setMessages(prev => prev.filter(msg => msg.id !== messageId));
    };

    socket.on("receive_message", handleReceiveMessage);
    socket.on("message_sent", handleMessageSent);
    socket.on("message_read", handleMessageRead);
    socket.on("message_deleted", handleMessageDeleted);

    return () => {
      socket.off("receive_message", handleReceiveMessage);
      socket.off("message_sent", handleMessageSent);
      socket.off("message_read", handleMessageRead);
      socket.off("message_deleted", handleMessageDeleted);
    };
  }, [socket, selectedUser, currentUser]);

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

  const sendMessage = async () => {
    if ((!inputText.trim() && !selectedFile) || !selectedUser || !socket) return;

    let attachmentData = null;

    if (selectedFile) {
      setIsUploading(true);
      const formData = new FormData();
      formData.append("file", selectedFile);

      try {
        const token = localStorage.getItem("token") || sessionStorage.getItem("token");
        const response = await axios.post(`${apiUrl}/api/chat/upload`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${token}`
          }
        });

        if (response.data.success) {
          attachmentData = response.data.data;
        }
      } catch (error) {
        console.error("Error uploading file:", error);
        alert("Failed to upload file. Please try again.");
        setIsUploading(false);
        return;
      }
      setIsUploading(false);
    }

    socket.emit("send_message", {
      receiverId: selectedUser.id,
      content: inputText.trim() || null,
      ...(attachmentData || {})
    });

    setInputText("");
    setSelectedFile(null);
    setShowEmojiPicker(false);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setSelectedFile(e.target.files[0]);
    }
  };

  const confirmDeleteChat = async () => {
    if (!selectedUser) return;
    const targetUserId = selectedUser.id;

    try {
      const token = localStorage.getItem("token") || sessionStorage.getItem("token");
      const response = await axios.delete(`${apiUrl}/api/chat/messages/${targetUserId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setMessages([]);
        setShowDeleteModal(false);
        toast.success("Chat deleted successfully");

        // Keep the user selected but without messages
        // setSelectedUser(null);

        // Also run the GET API to ensure state is completely synced
        try {
          const usersRes = await axios.get(`${apiUrl}/api/chat/users`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          if (usersRes.data.success) {
            setUsers(usersRes.data.data);
          }
        } catch (err) {
          console.error("Error re-fetching chat users after delete", err);
        }
      }
    } catch (error) {
      console.error("Error deleting chat:", error);
      toast.error("Failed to delete chat.");
      setShowDeleteModal(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  const filteredUsers = users.filter(user =>
    `${user.firstName} ${user.lastName}`.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const deleteSingleMessage = async (messageId: string) => {
    try {
      const token = localStorage.getItem("token") || sessionStorage.getItem("token");
      await axios.delete(`${apiUrl}/api/chat/messages/single/${messageId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      // The socket event 'message_deleted' will remove it from the UI for both users
    } catch (error) {
      console.error("Error deleting message", error);
      toast.error("Failed to delete message");
    }
  };

  const formatDateHeader = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-GB', { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' });
  };

  const groupedMessages: { [key: string]: ChatMessage[] } = {};
  messages.forEach(msg => {
    const dateStr = formatDateHeader(msg.createdAt);
    if (!groupedMessages[dateStr]) groupedMessages[dateStr] = [];
    groupedMessages[dateStr].push(msg);
  });

  return (
    <>
      <AuthGuard>
        <div className="flex h-screen w-full overflow-hidden bg-white">
          <div className={`${selectedUser && !showMobileSidebar ? '-translate-x-full md:translate-0 -ml-[100%] md:ml-0' : 'translate-0 ml-0'} w-full md:w-[350px] flex flex-col bg-brand-950 transition-all ease-in-out duration-300`}>
            <div className="p-3 border-b border-b-[#3a4e72] mb-3 flex gap-2">
              <button onClick={() => router.push('/')} className="text-gray-500 bg-yellow-500 rounded-full w-11 h-11 flex items-center justify-center shrink-0">
                <ArrowLeft size={20} className="text-brand-950" />
              </button>
              <div className="relative flex items-center w-full rounded-full bg-[#112546] px-3 py-3">
                <Search size={18} className="text-gray-400 mr-2" />
                <input type="text" placeholder="Search or start new chat" className="w-full bg-transparent text-sm outline-none placeholder-gray-400 text-white" value={searchQuery}  onChange={(e) => setSearchQuery(e.target.value)} />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto custom-scrollbar-dark space-y-1">
              {filteredUsers.length === 0 ? (
                <div className="p-4 text-center text-sm text-gray-400">No users found.</div>
              ) : (
                filteredUsers.map((user) => {
                  const isOnline = onlineUsers.includes(user.id);
                  const isSelected = selectedUser?.id === user.id;
                  return (
                    <button
                      key={user.id}
                      onClick={() => {
                        setSelectedUser(user);
                        setUsers(prev => prev.map(u => u.id === user.id ? { ...u, unreadCount: 0 } : u));
                        window.dispatchEvent(new CustomEvent('chat_read'));
                        setShowMobileSidebar(false);
                      }}
                      className={`flex w-full items-center gap-3 px-3 py-2.5 transition-colors hover:bg-[#364a6c] relative after:content-[''] after:absolute after:right-0 after:top-1/2 after:-translate-y-1/2 after:w-1 after:h-10 after:rounded-tl-sm after:rounded-bl-sm ${isSelected ? 'bg-[#364a6c] after:bg-yellow-500' : 'after:bg-transparent'}`}
                    >
                      <div className="relative h-10 w-10 shrink-0 rounded-full border border-[#364a6c]">
                        <ChatAvatar user={user} className="h-10 w-10" textSize="text-sm" />
                        {isOnline ? (
                          <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border border-white bg-green-500 z-10"></span>
                        ) : (
                          <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border border-white bg-red-500 z-10"></span>
                        )}
                      </div>
                      <div className="flex-1 overflow-hidden text-left">
                        <div className="flex items-center justify-between">
                          <p className={`truncate font-medium ${isSelected ? 'text-white' : 'text-gray-200'}`}>
                            {user.firstName} {user.lastName}
                          </p>
                        </div>
                        {/* <p className="truncate text-xs text-gray-300">
                          {isOnline ? "Active now" : "Offline"}
                        </p> */}
                      </div>
                      {user.unreadCount && user.unreadCount > 0 ? (
                        <div className="ml-2 flex h-5 min-w-[20px] items-center justify-center rounded-full bg-blue-500 px-1.5 text-xs font-semibold text-white">
                          {user.unreadCount}
                        </div>
                      ) : null}
                    </button>
                  );
                })
              )}
            </div>
          </div>

          {/* Main Chat Area */}
          <div className={`${!selectedUser || showMobileSidebar ? 'hidden md:flex' : 'flex'} flex-1 flex-col bg-[#f1f3f7]`}>
            {!selectedUser ? (
              <div className="flex h-full flex-col items-center justify-center bg-[#f0f2f5] p-4 text-center">
                <div className="mb-2">
                  <Image src={'/images/chat-blank.png'} alt="" width={500} height={500} className="w-auto h-auto max-w-[250px]" />
                </div>
                <h2 className="mb-2 text-3xl font-medium text-brand-950">Start a conversation</h2>
                <p className="text-base text-[#667781] max-w-md">
                  Send and receive messages in real-time.<br />
                  Select a user from the sidebar to start a conversation.
                </p>
              </div>
            ) : (
              <>
                {/* Chat Header */}
                <div className="flex h-[68px] items-center justify-between bg-white px-4 shadow-theme-lg z-10">
                  <div className="flex items-center gap-3">
                    <div className="relative h-10 w-10 shrink-0">
                      <ChatAvatar user={selectedUser} />
                      {onlineUsers.includes(selectedUser.id) ? (
                        <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border border-white bg-[#00a884] z-10"></span>
                      ) : (
                        <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border border-white bg-gray-400 z-10"></span>
                      )}
                    </div>
                    <div className="">
                      <h3 className="font-medium text-[#111b21] leading-tight">
                        {selectedUser.firstName} {selectedUser.lastName}
                      </h3>
                      <p className="text-[13px] text-[#667781]">
                        {onlineUsers.includes(selectedUser.id) ? "online" : "offline"}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4 text-[#54656f]">
                    <button 
                      className="p-1 mr-1 md:hidden"
                      onClick={() => setShowMobileSidebar(true)}
                    >
                      <Menu size={20} />
                    </button>
                    <button onClick={() => setShowDeleteModal(true)} className="hover:text-red-500 transition" title="Delete Chat">
                      <Trash2 size={20} />
                    </button>
                  </div>
                </div>

                {/* Chat Messages */}
                <div className="flex-1 overflow-y-auto p-4 custom-scrollbar bg-cover bg-center" style={{ backgroundImage: "url('/images/chat-bg.png')" }}>
                  {isLoading ? (
                    <div className="flex h-full items-center justify-center">
                      <span className="text-sm text-gray-500 bg-white/80 px-4 py-1 rounded-full shadow-sm">Loading messages...</span>
                    </div>
                  ) : messages.length === 0 ? (
                    <div className="flex h-full items-center justify-center">
                      <span className="text-sm text-gray-500 bg-white/80 px-4 py-1 rounded-full shadow-sm">Send a message to start the chat</span>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {Object.keys(groupedMessages).map((dateKey) => (
                        <React.Fragment key={dateKey}>
                          <div className="flex justify-center my-4">
                            <span className="bg-white/80 text-[#667781] text-[13px] leading-[15px] px-3 py-1.5 rounded-lg shadow-xs font-medium">
                              {dateKey}
                            </span>
                          </div>
                          {groupedMessages[dateKey].map((msg) => {
                            const isMe = msg.senderId === currentUser?.id;
                            return (
                              <div key={msg.id} className={`flex items-end gap-2 group ${isMe ? 'justify-end' : 'justify-start'}`}>
                                {!isMe && (
                                  <div className="relative h-8 w-8 flex-shrink-0 mb-1">
                                    <ChatAvatar user={selectedUser} className="h-8 w-8" textSize="text-xs" />
                                  </div>
                                )}
                                {isMe && ((currentTime - new Date(msg.createdAt).getTime()) / (1000 * 60) <= 5) && (
                                  <button onClick={() => deleteSingleMessage(msg.id)} className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 transition-opacity mb-2.5">
                                    <Trash2 size={16} />
                                  </button>
                                )}
                                <div className={`relative max-w-[80%] md:max-w-[65%] rounded-xl px-2 py-1.5 shadow-xs flex flex-col ${isMe
                                  ? 'bg-[#d9fdd3] text-[#111b21] rounded-tr-none'
                                  : 'bg-white text-[#111b21] rounded-tl-none'
                                  }`}>
                                  {msg.attachmentUrl && (
                                    <div className="mb-1 rounded overflow-hidden">
                                      {msg.attachmentType?.startsWith('image/') ? (
                                        <a href={msg.attachmentUrl} target="_blank" rel="noopener noreferrer">
                                          <img src={msg.attachmentUrl} alt="Attachment" className="max-w-[280px] max-h-[280px] w-auto h-auto object-cover rounded cursor-pointer hover:opacity-90 transition" />
                                        </a>
                                      ) : (
                                        <a
                                          href={msg.attachmentUrl}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className="flex items-center gap-2 p-3 bg-black/5 rounded-md hover:bg-black/10 transition"
                                        >
                                          <div className="bg-white p-2 rounded shadow-sm">
                                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-gray-500">
                                              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                                              <polyline points="14 2 14 8 20 8"></polyline>
                                              <line x1="16" y1="13" x2="8" y2="13"></line>
                                              <line x1="16" y1="17" x2="8" y2="17"></line>
                                              <polyline points="10 9 9 9 8 9"></polyline>
                                            </svg>
                                          </div>
                                          <div className="flex flex-col flex-1 min-w-0">
                                            <span className="text-sm font-medium truncate">{msg.attachmentName || 'Document'}</span>
                                            <span className="text-xs text-gray-500 uppercase">{msg.attachmentType?.split('/')[1] || 'FILE'}</span>
                                          </div>
                                        </a>
                                      )}
                                    </div>
                                  )}
                                  {msg.content && <div className="text-[14.2px] leading-[17px] break-words pr-[60px] pb-2.5 pl-1.5">{msg.content}</div>}
                                  <div className={`flex items-center justify-end gap-1 absolute right-2 bottom-1 ${isMe ? 'text-[#667781]' : 'text-[#667781]'}`}>
                                    <span className="text-[11px]">
                                      {new Date(msg.createdAt).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true })}
                                    </span>
                                    {isMe && (
                                      <span className={msg.isRead ? "text-blue-500" : "text-gray-400"}>
                                        <svg viewBox="0 0 16 15" width="16" height="15" fill="currentColor">
                                          <path d="M15.01 3.316l-.478-.372a.365.365 0 0 0-.51.063L8.666 9.879a.32.32 0 0 1-.484.033l-.358-.325a.319.319 0 0 0-.484.032l-.378.483a.418.418 0 0 0 .036.541l1.32 1.266c.143.14.361.125.484-.033l6.272-8.048a.366.366 0 0 0-.064-.512zm-4.1 0l-.478-.372a.365.365 0 0 0-.51.063L4.566 9.879a.32.32 0 0 1-.484.033L1.891 7.769a.366.366 0 0 0-.515.006l-.423.433a.364.364 0 0 0 .006.514l3.258 3.185c.143.14.361.125.484-.033l6.272-8.048a.365.365 0 0 0-.063-.51z" />
                                        </svg>
                                      </span>
                                    )}
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </React.Fragment>
                      ))}
                      <div ref={messagesEndRef} />
                    </div>
                  )}
                </div>

                {/* File Preview */}
                {selectedFile && (
                  <div className="bg-[#f0f2f5] px-4 py-3 border-t border-gray-200">
                    <div className="relative inline-block">
                      <div className="bg-white p-3 rounded-lg shadow-sm flex items-center gap-3 pr-10">
                        {selectedFile.type.startsWith('image/') ? (
                          <div className="relative h-16 w-16">
                            <img src={URL.createObjectURL(selectedFile)} alt="Preview" className="object-cover h-full w-full rounded" />
                          </div>
                        ) : (
                          <div className="h-12 w-12 bg-gray-100 flex items-center justify-center rounded">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-gray-500">
                              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                              <polyline points="14 2 14 8 20 8"></polyline>
                            </svg>
                          </div>
                        )}
                        <div className="flex flex-col max-w-[200px]">
                          <span className="text-sm font-medium truncate">{selectedFile.name}</span>
                          <span className="text-xs text-gray-500">{(selectedFile.size / 1024).toFixed(1)} KB</span>
                        </div>
                      </div>
                      <button
                        onClick={() => setSelectedFile(null)}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600 transition"
                      >
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                          <line x1="18" y1="6" x2="6" y2="18"></line>
                          <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                      </button>
                    </div>
                  </div>
                )}

                {/* Message Input */}
                <div className="px-4 pb-4">
                  <div className="flex items-center gap-1.5 md:gap-3 bg-white px-4 py-3 rounded-full shadow-theme-lg">
                    <input type="file" ref={fileInputRef} className="hidden" onChange={handleFileChange} />
                    <button onClick={() => fileInputRef.current?.click()} className="w-11 h-11 bg-[#f1f3f7] rounded-full flex items-center justify-center shrink-0">
                      <svg className="w-5 h-5" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
                      </svg>
                    </button>
                    <div className="relative flex items-center">
                      <button onClick={() => setShowEmojiPicker((prev) => !prev)} className="w-11 h-11 bg-[#f1f3f7] rounded-full flex items-center justify-center shrink-0">
                        <Smile size={20} className="text-brand-950" />
                      </button>
                      {showEmojiPicker && (
                        <div className="absolute bottom-full mb-2 left-0 z-50">
                          <EmojiPicker onEmojiClick={(emojiData) => setInputText(prev => prev + emojiData.emoji)} />
                        </div>
                      )}
                    </div>
                    <div className="relative flex flex-1 items-center bg-white rounded-full border border-[#f1f3f7]">
                      <input
                        type="text"
                        value={inputText}
                        onChange={(e) => setInputText(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder="Type a message"
                        className="w-full bg-transparent text-sm outline-none text-[#111b21] placeholder-[#8696a0] px-4 py-3"
                      />
                    </div>
                    <button
                      onClick={sendMessage}
                      disabled={(!inputText.trim() && !selectedFile) || isUploading}
                      className={`w-11 h-11 bg-brand-950 rounded-full flex items-center justify-center shrink-0 ${(!inputText.trim() && !selectedFile) || isUploading ? 'opacity-50' : 'text-white'}`}
                    >
                      {isUploading ? (
                        <div className="h-5 w-5 border-2 border-t-[#00a884] border-gray-300 rounded-full animate-spin"></div>
                      ) : (
                        <Send size={20} className="text-white" />
                      )}
                    </button>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>

        <Modal isOpen={showDeleteModal} onClose={() => setShowDeleteModal(false)} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 text-center">
              <h4 className="text-xl lg:text-2xl font-semibold text-brand-950 mb-4">
                Confirm Delete
              </h4>
              <p className="mb-10 text-sm text-gray-500 lg:mb-12">
                Are you sure you want to delete chat with <span className="font-semibold text-brand-950">{selectedUser?.firstName} {selectedUser?.lastName}</span>?
              </p>
            </div>
            <div className="flex items-center gap-3 mt-8 justify-center">
              <button
                onClick={() => setShowDeleteModal(false)}
                className="flex min-w-[120px] items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-brand-950 hover:bg-gray-100 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={confirmDeleteChat}
                className="inline-flex min-w-[120px] items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
              >
                Delete
              </button>
            </div>
          </div>
        </Modal>
      </AuthGuard>
    </>
  );
}
