"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 } 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 flex-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 flex-shrink-0 flex items-center justify-center rounded-full bg-blue-100 text-blue-600 font-semibold border border-gray-200 ${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 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-[calc(100vh-80px)] w-full overflow-hidden bg-white border border-gray-200 rounded-xl shadow-sm mt-4">
          {/* Sidebar - Users List */}
          <div className={`${selectedUser ? 'hidden md:flex' : 'flex'} w-full md:w-[350px] lg:w-[400px] flex-col border-r border-gray-200 bg-white`}>
            {/* Header */}
            <div className="flex h-[59px] items-center justify-between border-b border-gray-200 bg-[#f0f2f5] px-4 py-2.5">
              <div className="flex items-center gap-3">
                <button onClick={() => router.push('/')} className="text-gray-500 hover:text-gray-700 transition">
                  <ArrowLeft size={20} />
                </button>
                <div className="relative h-10 w-10 flex-shrink-0">
                  <ChatAvatar user={currentUser} className="h-10 w-10" textSize="text-lg" />
                </div>
                <h2 className="text-lg font-semibold text-gray-800">Chats</h2>
              </div>
            </div>

            {/* Search */}
            <div className="border-b border-gray-200 p-3">
              <div className="relative flex items-center w-full rounded-lg bg-gray-100 px-3 py-2">
                <Search size={18} className="text-gray-500 mr-2" />
                <input
                  type="text"
                  placeholder="Search or start new chat"
                  className="w-full bg-transparent text-sm outline-none placeholder-gray-500"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            {/* User List */}
            <div className="flex-1 overflow-y-auto custom-scrollbar">
              {filteredUsers.length === 0 ? (
                <div className="p-4 text-center text-sm text-gray-500">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'));
                      }}
                      className={`flex w-full items-center gap-3 border-b border-gray-100 p-3 transition-colors ${isSelected ? 'bg-gray-100' : 'hover:bg-gray-50'
                        }`}
                    >
                      <div className="relative h-12 w-12 flex-shrink-0">
                        <ChatAvatar user={user} className="h-12 w-12" textSize="text-lg" />
                        {isOnline ? (
                          <span className="absolute bottom-0 right-0 h-3.5 w-3.5 rounded-full border-2 border-white bg-green-500 z-10"></span>
                        ) : (
                          <span className="absolute bottom-0 right-0 h-3.5 w-3.5 rounded-full border-2 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-semibold text-gray-900">
                            {user.firstName} {user.lastName}
                          </p>
                        </div>
                        <p className="truncate text-sm text-gray-500">
                          {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 ? 'hidden md:flex' : 'flex'} flex-1 flex-col bg-[#efeae2]`}>
            {!selectedUser ? (
              <div className="flex h-full flex-col items-center justify-center bg-[#f0f2f5] px-4 text-center">
                <div className="mb-6 rounded-full bg-[#00a884]/10 p-6 text-[#00a884]">
                  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" />
                  </svg>
                </div>
                <h2 className="mb-2 text-3xl font-light text-[#41525d]">PMS Chat</h2>
                <p className="text-[14px] text-[#8696a0] max-w-md mt-4">
                  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-[70px] items-center justify-between bg-[#f0f2f5] px-4 shadow-sm z-10 border-l border-gray-300">
                  <div className="flex items-center gap-3">
                    <div className="relative h-10 w-10 flex-shrink-0 cursor-pointer">
                      <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="cursor-pointer">
                      <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 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-[#54656f] text-xs px-3 py-1 rounded-md shadow-sm 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 && (
                                  <button onClick={() => deleteSingleMessage(msg.id)} className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 transition-opacity mb-2">
                                    <Trash2 size={16} />
                                  </button>
                                )}
                                <div className={`relative max-w-[80%] md:max-w-[65%] rounded-lg px-2 py-1.5 shadow-sm 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-[19px] break-words pr-[60px] pb-3 pl-1.5 pt-0.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-300">
                    <div className="relative inline-block">
                      <div className="bg-white p-3 rounded-lg shadow-sm border border-gray-200 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="flex items-center gap-3 bg-[#f0f2f5] px-4 py-3">
                  <input
                    type="file"
                    ref={fileInputRef}
                    className="hidden"
                    onChange={handleFileChange}
                  />
                  <button
                    onClick={() => fileInputRef.current?.click()}
                    className="text-[#54656f] hover:text-[#111b21] transition hover:bg-gray-200 rounded-full p-2"
                  >
                    <svg 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="text-[#54656f] hover:text-[#111b21] transition hover:bg-gray-200 rounded-full p-2"
                    >
                      <Smile size={24} className="text-[#54656f]" />
                    </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-lg px-3 py-2 shadow-sm">
                    <input
                      type="text"
                      value={inputText}
                      onChange={(e) => setInputText(e.target.value)}
                      onKeyDown={handleKeyDown}
                      placeholder="Type a message"
                      className="w-full bg-transparent text-[15px] outline-none text-[#111b21] placeholder-[#8696a0]"
                    />
                  </div>
                  <button
                    onClick={sendMessage}
                    disabled={(!inputText.trim() && !selectedFile) || isUploading}
                    className={`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full text-[#54656f] transition hover:text-[#111b21] ${(!inputText.trim() && !selectedFile) || isUploading ? 'opacity-50' : 'text-[#00a884]'}`}
                  >
                    {isUploading ? (
                      <div className="h-5 w-5 border-2 border-t-[#00a884] border-gray-300 rounded-full animate-spin"></div>
                    ) : (
                      <Send size={24} className={inputText.trim() || selectedFile ? "text-[#00a884]" : ""} />
                    )}
                  </button>
                </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>
    </>
  );
}
