import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { 
  Users as UsersIcon, 
  Search, 
  Filter, 
  Plus, 
  MoreVertical,
  Edit,
  Trash2,
  Key,
  Crown,
  UserCheck,
  EyeOff,
  RefreshCw,
  Download,
  Upload,
  Settings,
  Eye
} from 'lucide-react'
import { usersAPI } from '../services/api'
import toast from 'react-hot-toast'
import UserModal from '../components/UserModal'
import Modal from '../components/Modal'

const Users = () => {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedUsers, setSelectedUsers] = useState([])
  const [showAddModal, setShowAddModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [editingUser, setEditingUser] = useState(null)
  const [deletingUser, setDeletingUser] = useState(null)
  const [filterType, setFilterType] = useState('all')
  const [sortBy, setSortBy] = useState('date_joined')
  const [sortOrder, setSortOrder] = useState('desc')
  const [refreshing, setRefreshing] = useState(false)

  const { data: users, isLoading, refetch } = useQuery({
    queryKey: ['users'],
    queryFn: usersAPI.getUsers,
    placeholderData: [], // Provide empty array as placeholder
  })

  const handleRefresh = async () => {
    setRefreshing(true)
    try {
      await refetch()
      toast.success('Users refreshed successfully')
    } catch (error) {
      toast.error('Failed to refresh users')
    } finally {
      setRefreshing(false)
    }
  }

  const handleCreateUser = async (userData) => {
    try {
      await usersAPI.createUser(userData)
      await refetch()
    } catch (error) {
      throw error
    }
  }

  const handleUpdateUser = async (userData) => {
    try {
      await usersAPI.updateUser(editingUser.id, userData)
      await refetch()
    } catch (error) {
      throw error
    }
  }

  const handleDeleteUser = async () => {
    if (!deletingUser) return
    
    try {
      await usersAPI.deleteUser(deletingUser.id)
      toast.success('User deleted successfully')
      setShowDeleteModal(false)
      setDeletingUser(null)
      await refetch()
    } catch (error) {
      toast.error('Failed to delete user')
    }
  }

  const handleUpdateSubscription = async (userId, subscriptionType) => {
    try {
      await usersAPI.updateSubscription({ user_id: userId, subscription_type: subscriptionType })
      toast.success('Subscription updated successfully')
      refetch()
    } catch (error) {
      toast.error('Failed to update subscription')
    }
  }

  const handleToggleApiAccess = async (userId) => {
    try {
      await usersAPI.toggleApiAccess({ user_id: userId })
      toast.success('API access toggled successfully')
      refetch()
    } catch (error) {
      toast.error('Failed to toggle API access')
    }
  }

  const handleEditUser = (user) => {
    setEditingUser(user)
    setShowEditModal(true)
  }

  const handleDeleteClick = (user) => {
    setDeletingUser(user)
    setShowDeleteModal(true)
  }

  const handleBulkAction = async (action) => {
    if (selectedUsers.length === 0) {
      toast.error('Please select users first')
      return
    }

    try {
      switch (action) {
        case 'delete':
          // Implement bulk delete
          toast.success(`${selectedUsers.length} users deleted`)
          break
        case 'export':
          // Implement bulk export
          toast.success('Users exported successfully')
          break
        default:
          break
      }
      setSelectedUsers([])
    } catch (error) {
      toast.error('Bulk action failed')
    }
  }

  const getSubscriptionBadge = (type) => {
    const badges = {
      free: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200',
      paid: 'bg-slate-100 text-slate-800 dark:bg-slate-900/20 dark:text-slate-400',
      premium: 'bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-400',
    }
    return badges[type] || badges.free
  }

  // Mock data for demonstration when backend is not available
  const mockUsers = [
    {
      id: 1,
      email: 'admin@example.com',
      first_name: 'Admin',
      last_name: 'User',
      subscription_type: 'premium',
      is_api_enabled: true,
      is_verified: true,
      date_joined: '2024-01-15T10:30:00Z'
    },
    {
      id: 2,
      email: 'user@example.com',
      first_name: 'John',
      last_name: 'Doe',
      subscription_type: 'free',
      is_api_enabled: false,
      is_verified: true,
      date_joined: '2024-02-01T14:20:00Z'
    }
  ]

  const displayUsers = users && users.length > 0 ? users : mockUsers
  const filteredUsers = displayUsers?.filter(user =>
    user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.first_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    user.last_name?.toLowerCase().includes(searchTerm.toLowerCase())
  ) || []

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary-600"></div>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="bg-gradient-to-r from-slate-800 via-slate-700 to-slate-600 rounded-2xl p-8 text-white shadow-2xl">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold mb-2 tracking-tight">
              User Management
            </h1>
            <p className="text-slate-200 text-base font-normal">
              Manage user accounts, permissions, and subscriptions
            </p>
            <div className="flex items-center mt-4 space-x-6">
              <div className="flex items-center space-x-2">
                <UsersIcon className="h-5 w-5 text-green-300" />
                <span className="text-sm font-medium">{displayUsers?.length || 0} Total Users</span>
              </div>
              <div className="flex items-center space-x-2">
                <UserCheck className="h-5 w-5 text-slate-300" />
                <span className="text-sm font-medium">{displayUsers?.filter(u => u.is_verified)?.length || 0} Verified</span>
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-4">
            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-200 rounded-lg px-4 py-2 flex items-center space-x-2"
            >
              <RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
              <span>Refresh</span>
            </button>
            
            <button
              onClick={() => setShowAddModal(true)}
              className="bg-white text-slate-700 hover:bg-slate-50 transition-all duration-200 rounded-lg px-6 py-2 font-semibold flex items-center space-x-2"
            >
              <Plus className="h-4 w-4" />
              <span>Add User</span>
            </button>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-8">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white">Search & Filter</h3>
          <div className="flex items-center space-x-2">
            <Filter className="h-5 w-5 text-gray-400" />
            <span className="text-sm text-gray-500">Advanced Filters</span>
          </div>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search users by name, email..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
            />
          </div>
          
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value)}
            className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          >
            <option value="all">All Users</option>
            <option value="free">Free</option>
            <option value="paid">Paid</option>
            <option value="premium">Premium</option>
            <option value="verified">Verified</option>
            <option value="api_enabled">API Enabled</option>
          </select>
          
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          >
            <option value="date_joined">Date Joined</option>
            <option value="first_name">First Name</option>
            <option value="last_name">Last Name</option>
            <option value="email">Email</option>
            <option value="subscription_type">Subscription</option>
          </select>
          
          <button
            onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
            className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 font-medium rounded-lg transition-all duration-200 flex items-center justify-center space-x-2 text-sm"
          >
            <span>{sortOrder === 'asc' ? '↑' : '↓'}</span>
            <span>Sort</span>
          </button>
        </div>
      </div>

      {/* Users Table */}
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="px-8 py-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white">Users</h3>
            <div className="flex items-center space-x-4">
              {selectedUsers.length > 0 && (
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-gray-600 dark:text-gray-400">
                    {selectedUsers.length} selected
                  </span>
                  <button
                    onClick={() => handleBulkAction('export')}
                    className="px-2 py-1 bg-slate-100 dark:bg-slate-900/20 text-slate-600 dark:text-slate-400 text-xs font-medium rounded-md hover:bg-slate-200 dark:hover:bg-slate-900/30 transition-colors"
                  >
                    Export
                  </button>
                  <button
                    onClick={() => handleBulkAction('delete')}
                    className="px-2 py-1 bg-red-100 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-medium rounded-md hover:bg-red-200 dark:hover:bg-red-900/30 transition-colors"
                  >
                    Delete
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th className="px-6 py-4 text-left">
                  <input
                    type="checkbox"
                    className="w-4 h-4 text-slate-600 bg-gray-100 border-gray-300 rounded focus:ring-slate-500 dark:focus:ring-slate-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedUsers(filteredUsers.map(user => user.id))
                      } else {
                        setSelectedUsers([])
                      }
                    }}
                  />
                </th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">User</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Subscription</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">API Access</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Status</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Joined</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {filteredUsers.map((user, index) => (
                <tr key={user.id} className={`hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200 ${index % 2 === 0 ? 'bg-white dark:bg-gray-800' : 'bg-gray-50/50 dark:bg-gray-800/50'}`}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <input
                      type="checkbox"
                      className="w-4 h-4 text-slate-600 bg-gray-100 border-gray-300 rounded focus:ring-slate-500 dark:focus:ring-slate-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                      checked={selectedUsers.includes(user.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedUsers([...selectedUsers, user.id])
                        } else {
                          setSelectedUsers(selectedUsers.filter(id => id !== user.id))
                        }
                      }}
                    />
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center space-x-4">
                      <div className="w-12 h-12 bg-gradient-to-br from-slate-500 to-slate-600 rounded-xl flex items-center justify-center shadow-lg">
                        <span className="text-lg font-bold text-white">
                          {user.first_name?.[0] || user.email[0].toUpperCase()}
                        </span>
                      </div>
                      <div>
                        <p className="text-lg font-semibold text-gray-900 dark:text-white">
                          {user.first_name} {user.last_name}
                        </p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                          {user.email}
                        </p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold ${getSubscriptionBadge(user.subscription_type)}`}>
                      {user.subscription_type === 'premium' && <Crown className="h-4 w-4 mr-1" />}
                      {user.subscription_type}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold ${
                      user.is_api_enabled 
                        ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400'
                        : 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'
                    }`}>
                      {user.is_api_enabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold ${
                      user.is_verified 
                        ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400'
                        : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400'
                    }`}>
                      {user.is_verified ? 'Verified' : 'Pending'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                    {new Date(user.date_joined).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => handleEditUser(user)}
                        className="p-2 text-slate-600 hover:text-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900/20 rounded-lg transition-all duration-200"
                        title="Edit User"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleUpdateSubscription(user.id, user.subscription_type === 'free' ? 'paid' : 'free')}
                        className="p-2 text-purple-600 hover:text-purple-800 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded-lg transition-all duration-200"
                        title="Change Subscription"
                      >
                        <Crown className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleToggleApiAccess(user.id)}
                        className={`p-2 rounded-lg transition-all duration-200 ${
                          user.is_api_enabled 
                            ? 'text-green-600 hover:text-green-800 hover:bg-green-50 dark:hover:bg-green-900/20' 
                            : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
                        }`}
                        title={user.is_api_enabled ? 'Disable API Access' : 'Enable API Access'}
                      >
                        {user.is_api_enabled ? <Key className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
                      </button>
                      <button
                        onClick={() => handleDeleteClick(user)}
                        className="p-2 text-red-600 hover:text-red-800 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-all duration-200"
                        title="Delete User"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
              Showing <span className="font-bold">{filteredUsers.length}</span> of <span className="font-bold">{displayUsers?.length || 0}</span> users
            </p>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-500">Rows per page:</span>
              <select className="px-2 py-1 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm">
                <option>10</option>
                <option>25</option>
                <option>50</option>
                <option>100</option>
              </select>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <button className="px-3 py-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
              Previous
            </button>
            <button className="px-3 py-1.5 text-xs font-medium text-white bg-slate-600 rounded-md hover:bg-slate-700 transition-colors">
              1
            </button>
            <button className="px-3 py-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
              2
            </button>
            <button className="px-3 py-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors">
              Next
            </button>
          </div>
        </div>
      </div>

      {/* Modals */}
      <UserModal
        isOpen={showAddModal}
        onClose={() => setShowAddModal(false)}
        onSave={handleCreateUser}
        mode="create"
      />

      <UserModal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false)
          setEditingUser(null)
        }}
        onSave={handleUpdateUser}
        user={editingUser}
        mode="edit"
      />

      <Modal
        isOpen={showDeleteModal}
        onClose={() => {
          setShowDeleteModal(false)
          setDeletingUser(null)
        }}
        title="Delete User"
        size="sm"
      >
        <div className="text-center">
          <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900/20 mb-4">
            <Trash2 className="h-6 w-6 text-red-600 dark:text-red-400" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            Are you sure?
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
            This will permanently delete <strong>{deletingUser?.first_name} {deletingUser?.last_name}</strong> and all their data. This action cannot be undone.
          </p>
          <div className="flex items-center justify-center space-x-3">
            <button
              onClick={() => {
                setShowDeleteModal(false)
                setDeletingUser(null)
              }}
              className="btn btn-secondary"
            >
              Cancel
            </button>
            <button
              onClick={handleDeleteUser}
              className="btn btn-danger"
            >
              <Trash2 className="h-4 w-4 mr-2" />
              Delete User
            </button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default Users

