import React, { useState, useMemo } from 'react';
import { Search, LogOut, Settings, UserPlus, MessageCircle, Users } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { formatConversationTime } from '../../utils/dateFormatter';

const Sidebar = ({ 
  conversations, 
  selectedConversation, 
  onSelectConversation, 
  onNewConversation,
  onlineUsers 
}) => {
  const { user, logout } = useAuth();
  const [searchTerm, setSearchTerm] = useState('');

  const filteredConversations = useMemo(() => {
    if (!searchTerm) return conversations;
    
    return conversations.filter(conv => {
      if (conv.type === 'direct') {
        const otherParticipant = conv.participants.find(p => p.user._id !== user.id);
        return otherParticipant?.user.displayName.toLowerCase().includes(searchTerm.toLowerCase()) ||
               otherParticipant?.user.username.toLowerCase().includes(searchTerm.toLowerCase());
      } else {
        return conv.name.toLowerCase().includes(searchTerm.toLowerCase());
      }
    });
  }, [conversations, searchTerm, user.id]);

  const getConversationDisplay = (conversation) => {
    if (conversation.type === 'direct') {
      const otherParticipant = conversation.participants.find(p => p.user._id !== user.id);
      return {
        name: otherParticipant?.user.displayName || 'Unknown User',
        avatar: otherParticipant?.user.avatar,
        status: otherParticipant?.user.status,
        isOnline: onlineUsers.has(otherParticipant?.user._id)
      };
    } else {
      return {
        name: conversation.name,
        avatar: conversation.avatar,
        isGroup: true
      };
    }
  };

  const getLastMessagePreview = (conversation) => {
    if (!conversation.lastMessage) return 'No messages yet';
    
    const lastMessage = conversation.lastMessage;
    if (lastMessage.type === 'image') return '📷 Image';
    if (lastMessage.type === 'audio') return '🎵 Audio';
    if (lastMessage.type === 'file') return '📎 File';
    
    return lastMessage.content.length > 30 
      ? lastMessage.content.substring(0, 30) + '...' 
      : lastMessage.content;
  };

  const handleLogout = async () => {
    if (window.confirm('Are you sure you want to logout?')) {
      await logout();
    }
  };

  return (
    <div className="flex flex-col h-full bg-white dark:bg-gray-800">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-primary-500 rounded-full flex items-center justify-center">
              <MessageCircle className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-lg font-bold text-gray-900 dark:text-white">YSNRFD</h1>
              <p className="text-xs text-gray-500 dark:text-gray-400">Messenger</p>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <button
              onClick={onNewConversation}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="New conversation"
            >
              <UserPlus size={20} />
            </button>
            <button
              onClick={handleLogout}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="Logout"
            >
              <LogOut size={20} />
            </button>
          </div>
        </div>

        {/* Search Bar */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="Search conversations..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
          />
        </div>
      </div>

      {/* Conversations List */}
      <div className="flex-1 overflow-y-auto scrollbar-thin">
        {filteredConversations.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full p-8 text-center">
            <Users className="w-16 h-16 text-gray-300 dark:text-gray-600 mb-4" />
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
              {searchTerm ? 'No conversations found' : 'No conversations yet'}
            </h3>
            <p className="text-gray-500 dark:text-gray-400 mb-4">
              {searchTerm 
                ? 'Try adjusting your search terms' 
                : 'Start a new conversation to begin messaging'
              }
            </p>
            {!searchTerm && (
              <button
                onClick={onNewConversation}
                className="btn-primary"
              >
                Start Conversation
              </button>
            )}
          </div>
        ) : (
          <div className="p-2">
            {filteredConversations.map((conversation) => {
              const display = getConversationDisplay(conversation);
              const isSelected = selectedConversation?._id === conversation._id;
              
              return (
                <div
                  key={conversation._id}
                  onClick={() => onSelectConversation(conversation)}
                  className={`sidebar-item ${isSelected ? 'sidebar-item-active' : ''}`}
                >
                  {/* Avatar */}
                  <div className="relative flex-shrink-0">
                    <div className="w-12 h-12 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white font-medium text-sm">
                      {display.avatar ? (
                        <img
                          src={display.avatar}
                          alt={display.name}
                          className="w-12 h-12 rounded-full object-cover"
                        />
                      ) : (
                        display.name.charAt(0).toUpperCase()
                      )}
                    </div>
                    
                    {/* Online Status Indicator */}
                    {display.isOnline && (
                      <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white dark:border-gray-800 rounded-full"></div>
                    )}
                    
                    {/* Group Indicator */}
                    {display.isGroup && (
                      <div className="absolute bottom-0 right-0 w-3 h-3 bg-blue-500 border-2 border-white dark:border-gray-800 rounded-full flex items-center justify-center">
                        <Users className="w-2 h-2 text-white" />
                      </div>
                    )}
                  </div>

                  {/* Conversation Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <h3 className="text-sm font-semibold text-gray-900 dark:text-white truncate">
                        {display.name}
                      </h3>
                      {conversation.lastMessage && (
                        <span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">
                          {formatConversationTime(conversation.lastMessage.createdAt)}
                        </span>
                      )}
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <p className="text-sm text-gray-500 dark:text-gray-400 truncate">
                        {getLastMessagePreview(conversation)}
                      </p>
                      
                      {/* Unread message indicator */}
                      {conversation.unreadCount > 0 && (
                        <span className="bg-primary-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center flex-shrink-0">
                          {conversation.unreadCount}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* User Profile Footer */}
      <div className="p-4 border-t border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white font-medium text-sm">
            {user.avatar ? (
              <img
                src={user.avatar}
                alt={user.displayName}
                className="w-10 h-10 rounded-full object-cover"
              />
            ) : (
              user.displayName.charAt(0).toUpperCase()
            )}
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="text-sm font-semibold text-gray-900 dark:text-white truncate">
              {user.displayName}
            </h3>
            <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
              @{user.username}
            </p>
          </div>
          <div className="w-2 h-2 bg-green-500 rounded-full" title="Online"></div>
        </div>
      </div>
    </div>
  );
};

export default Sidebar;