import React, { useState, useEffect } from 'react';
import { Search, X, User, UserPlus, MessageCircle } from 'lucide-react';
import { userService, conversationService } from '../../services/api';
import { useAuth } from '../../contexts/AuthContext';

const UserSearch = ({ onClose, onConversationCreated }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedUsers, setSelectedUsers] = useState(new Set());
  const [conversationName, setConversationName] = useState('');
  const [creating, setCreating] = useState(false);
  const { user } = useAuth();

  useEffect(() => {
    const searchUsers = async () => {
      if (!searchTerm.trim()) {
        setSearchResults([]);
        return;
      }

      setLoading(true);
      try {
        const response = await userService.search(searchTerm);
        // Filter out current user and already selected users
        const filteredResults = response.users.filter(
          u => u._id !== user.id && !selectedUsers.has(u._id)
        );
        setSearchResults(filteredResults);
      } catch (error) {
        console.error('Search error:', error);
        setSearchResults([]);
      } finally {
        setLoading(false);
      }
    };

    const timeoutId = setTimeout(searchUsers, 300);
    return () => clearTimeout(timeoutId);
  }, [searchTerm, selectedUsers, user.id]);

  const handleUserSelect = (user) => {
    setSelectedUsers(prev => {
      const newSet = new Set(prev);
      if (newSet.has(user._id)) {
        newSet.delete(user._id);
      } else {
        newSet.add(user._id);
      }
      return newSet;
    });
    setSearchTerm('');
    setSearchResults([]);
  };

  const handleRemoveUser = (userId) => {
    setSelectedUsers(prev => {
      const newSet = new Set(prev);
      newSet.delete(userId);
      return newSet;
    });
  };

  const createConversation = async () => {
    if (selectedUsers.size === 0) return;

    setCreating(true);
    try {
      const participantIds = Array.from(selectedUsers);
      
      let conversationData;
      if (participantIds.length === 1) {
        // Direct message
        conversationData = {
          type: 'direct',
          participantIds
        };
      } else {
        // Group chat
        conversationData = {
          type: 'group',
          name: conversationName || `Group with ${participantIds.length + 1} people`,
          participantIds
        };
      }

      const response = await conversationService.create(conversationData);
      onConversationCreated(response.conversation);
    } catch (error) {
      console.error('Create conversation error:', error);
      alert(error.error || 'Failed to create conversation');
    } finally {
      setCreating(false);
    }
  };

  const getSelectedUsersInfo = () => {
    return Array.from(selectedUsers).map(userId => {
      // In a real app, you'd have the user objects cached
      return { _id: userId, displayName: 'User', username: 'user' };
    });
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-xl w-full max-w-md max-h-[90vh] overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center space-x-3">
            <MessageCircle className="w-6 h-6 text-primary-500" />
            <h2 className="text-xl font-bold text-gray-900 dark:text-white">
              New Conversation
            </h2>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500 dark:text-gray-400" />
          </button>
        </div>

        <div className="p-6 space-y-4">
          {/* Search Input */}
          <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 users by username..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-3 bg-gray-50 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-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
            />
          </div>

          {/* Selected Users */}
          {selectedUsers.size > 0 && (
            <div className="space-y-2">
              <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Selected Users ({selectedUsers.size})
              </h3>
              <div className="flex flex-wrap gap-2">
                {getSelectedUsersInfo().map(user => (
                  <div
                    key={user._id}
                    className="flex items-center space-x-2 bg-primary-100 dark:bg-primary-900 px-3 py-1 rounded-full"
                  >
                    <span className="text-sm text-primary-700 dark:text-primary-300">
                      {user.displayName}
                    </span>
                    <button
                      onClick={() => handleRemoveUser(user._id)}
                      className="text-primary-500 hover:text-primary-700"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Group Name Input (for groups) */}
          {selectedUsers.size > 1 && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Group Name
              </label>
              <input
                type="text"
                placeholder="Enter group name..."
                value={conversationName}
                onChange={(e) => setConversationName(e.target.value)}
                className="w-full px-4 py-3 bg-gray-50 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-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
              />
            </div>
          )}

          {/* Search Results */}
          <div className="max-h-60 overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-500"></div>
              </div>
            ) : searchResults.length > 0 ? (
              <div className="space-y-2">
                <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Search Results
                </h3>
                {searchResults.map(user => (
                  <div
                    key={user._id}
                    onClick={() => handleUserSelect(user)}
                    className="flex items-center space-x-3 p-3 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg cursor-pointer transition-colors"
                  >
                    <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">
                      <h4 className="text-sm font-medium text-gray-900 dark:text-white truncate">
                        {user.displayName}
                      </h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400 truncate">
                        @{user.username}
                      </p>
                    </div>
                    <UserPlus className="w-4 h-4 text-gray-400" />
                  </div>
                ))}
              </div>
            ) : searchTerm && !loading ? (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                <User className="w-12 h-12 mx-auto mb-2 opacity-50" />
                <p>No users found</p>
              </div>
            ) : null}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="btn-secondary"
          >
            Cancel
          </button>
          <button
            onClick={createConversation}
            disabled={selectedUsers.size === 0 || creating}
            className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {creating ? (
              <div className="flex items-center space-x-2">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                <span>Creating...</span>
              </div>
            ) : (
              `Start ${selectedUsers.size === 1 ? 'Chat' : 'Group'}`
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default UserSearch;