import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { adminApi } from '@/api/admin'
import { Button } from '@/components/common/Button'
import { Loading } from '@/components/common/Loading'
import { Search, User, Shield, Ban, DollarSign, Edit, ChevronLeft, ChevronRight } from 'lucide-react'
import toast from 'react-hot-toast'
import type { AdminUser, BalanceAdjustRequest } from '@/types/admin'

export const AdminUsers = () => {
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [searchInput, setSearchInput] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null)
  const [showBalanceModal, setShowBalanceModal] = useState(false)
  const [balanceAmount, setBalanceAmount] = useState('')
  const [balanceReason, setBalanceReason] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['admin-users', page, search, statusFilter],
    queryFn: () =>
      adminApi.getUsers({
        page,
        page_size: 20,
        search: search || undefined,
        status_filter: statusFilter || undefined,
      }),
  })

  const statusMutation = useMutation({
    mutationFn: ({ userId, status }: { userId: number; status: 'active' | 'suspended' }) =>
      adminApi.changeUserStatus(userId, { status }),
    onSuccess: () => {
      toast.success('User status updated')
      queryClient.invalidateQueries({ queryKey: ['admin-users'] })
      setSelectedUser(null)
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to update status')
    },
  })

  const adminMutation = useMutation({
    mutationFn: ({ userId, isAdmin }: { userId: number; isAdmin: boolean }) =>
      adminApi.updateUser(userId, { is_admin: isAdmin }),
    onSuccess: () => {
      toast.success('Admin privileges updated')
      queryClient.invalidateQueries({ queryKey: ['admin-users'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to update privileges')
    },
  })

  const balanceMutation = useMutation({
    mutationFn: ({ userId, data }: { userId: number; data: BalanceAdjustRequest }) =>
      adminApi.adjustUserBalance(userId, data),
    onSuccess: (data) => {
      toast.success(`Balance adjusted: $${data.previous_balance} → $${data.new_balance}`)
      queryClient.invalidateQueries({ queryKey: ['admin-users'] })
      setShowBalanceModal(false)
      setSelectedUser(null)
      setBalanceAmount('')
      setBalanceReason('')
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to adjust balance')
    },
  })

  const handleSearch = () => {
    setSearch(searchInput)
    setPage(1)
  }

  const handleBalanceSubmit = () => {
    if (!selectedUser || !balanceAmount || !balanceReason) return
    balanceMutation.mutate({
      userId: selectedUser.id,
      data: {
        amount: parseFloat(balanceAmount),
        reason: balanceReason,
      },
    })
  }

  if (isLoading) {
    return <Loading />
  }

  const totalPages = data ? Math.ceil(data.total / data.page_size) : 1

  return (
    <div className="space-y-6">
      {/* Search and Filters */}
      <div className="bg-white rounded-lg shadow p-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 flex gap-2">
            <input
              type="text"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              placeholder="Search by username, email, or name..."
              className="flex-1 px-3 py-2 border border-gray-300 rounded-lg"
            />
            <Button onClick={handleSearch}>
              <Search size={18} />
            </Button>
          </div>

          <select
            value={statusFilter}
            onChange={(e) => {
              setStatusFilter(e.target.value)
              setPage(1)
            }}
            className="px-3 py-2 border border-gray-300 rounded-lg"
          >
            <option value="">All Status</option>
            <option value="active">Active</option>
            <option value="suspended">Suspended</option>
          </select>
        </div>
      </div>

      {/* Users Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="text-left px-4 py-3 text-sm font-semibold text-gray-600">User</th>
                <th className="text-left px-4 py-3 text-sm font-semibold text-gray-600">Status</th>
                <th className="text-left px-4 py-3 text-sm font-semibold text-gray-600">Balance</th>
                <th className="text-left px-4 py-3 text-sm font-semibold text-gray-600">Stats</th>
                <th className="text-left px-4 py-3 text-sm font-semibold text-gray-600">Joined</th>
                <th className="text-right px-4 py-3 text-sm font-semibold text-gray-600">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {data?.users.map((user) => (
                <tr key={user.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
                        <User size={20} className="text-gray-500" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-medium text-gray-900">{user.username}</span>
                          {user.is_admin && (
                            <Shield size={14} className="text-blue-500" title="Admin" />
                          )}
                        </div>
                        <p className="text-sm text-gray-500">{user.email}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`px-2 py-1 rounded-full text-xs font-medium ${
                        user.status === 'active'
                          ? 'bg-green-100 text-green-800'
                          : user.status === 'suspended'
                          ? 'bg-red-100 text-red-800'
                          : 'bg-yellow-100 text-yellow-800'
                      }`}
                    >
                      {user.status}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div>
                      <p className="font-medium text-gray-900">${Number(user.balance).toFixed(2)}</p>
                      {Number(user.escrow) > 0 && (
                        <p className="text-xs text-gray-500">+ ${Number(user.escrow).toFixed(2)} escrow</p>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm">
                      <p className="text-gray-900">
                        {user.wins}W / {user.losses}L
                      </p>
                      <p className="text-gray-500">{(user.win_rate * 100).toFixed(0)}% win rate</p>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-500">
                    {new Date(user.created_at).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-2">
                      <button
                        onClick={() => {
                          setSelectedUser(user)
                          setShowBalanceModal(true)
                        }}
                        className="p-1.5 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded"
                        title="Adjust Balance"
                      >
                        <DollarSign size={18} />
                      </button>
                      <button
                        onClick={() =>
                          statusMutation.mutate({
                            userId: user.id,
                            status: user.status === 'active' ? 'suspended' : 'active',
                          })
                        }
                        className={`p-1.5 rounded ${
                          user.status === 'active'
                            ? 'text-gray-500 hover:text-red-600 hover:bg-red-50'
                            : 'text-gray-500 hover:text-green-600 hover:bg-green-50'
                        }`}
                        title={user.status === 'active' ? 'Suspend User' : 'Activate User'}
                      >
                        <Ban size={18} />
                      </button>
                      <button
                        onClick={() =>
                          adminMutation.mutate({
                            userId: user.id,
                            isAdmin: !user.is_admin,
                          })
                        }
                        className={`p-1.5 rounded ${
                          user.is_admin
                            ? 'text-blue-500 hover:text-gray-600 hover:bg-gray-50'
                            : 'text-gray-500 hover:text-blue-600 hover:bg-blue-50'
                        }`}
                        title={user.is_admin ? 'Remove Admin' : 'Make Admin'}
                      >
                        <Shield size={18} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t bg-gray-50">
            <p className="text-sm text-gray-600">
              Showing {(page - 1) * 20 + 1} to {Math.min(page * 20, data?.total || 0)} of {data?.total || 0} users
            </p>
            <div className="flex gap-2">
              <Button
                variant="secondary"
                onClick={() => setPage(page - 1)}
                disabled={page === 1}
              >
                <ChevronLeft size={18} />
              </Button>
              <Button
                variant="secondary"
                onClick={() => setPage(page + 1)}
                disabled={page >= totalPages}
              >
                <ChevronRight size={18} />
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Balance Adjustment Modal */}
      {showBalanceModal && selectedUser && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 p-6">
            <h3 className="text-xl font-bold text-gray-900 mb-4">Adjust Balance</h3>

            <div className="mb-4 p-3 bg-gray-50 rounded-lg">
              <p className="text-sm text-gray-600">User: <span className="font-medium">{selectedUser.username}</span></p>
              <p className="text-sm text-gray-600">Current Balance: <span className="font-medium">${Number(selectedUser.balance).toFixed(2)}</span></p>
            </div>

            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-gray-700 font-medium mb-1">Amount (+ to add, - to subtract)</label>
                <input
                  type="number"
                  value={balanceAmount}
                  onChange={(e) => setBalanceAmount(e.target.value)}
                  placeholder="e.g., 100 or -50"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                />
              </div>

              <div>
                <label className="block text-gray-700 font-medium mb-1">Reason</label>
                <textarea
                  value={balanceReason}
                  onChange={(e) => setBalanceReason(e.target.value)}
                  placeholder="Reason for adjustment..."
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg"
                />
              </div>
            </div>

            <div className="flex gap-3">
              <Button
                variant="secondary"
                onClick={() => {
                  setShowBalanceModal(false)
                  setSelectedUser(null)
                  setBalanceAmount('')
                  setBalanceReason('')
                }}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button
                onClick={handleBalanceSubmit}
                disabled={!balanceAmount || !balanceReason || balanceMutation.isPending}
                className="flex-1"
              >
                {balanceMutation.isPending ? 'Adjusting...' : 'Adjust Balance'}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
