import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import { adminApi } from '@/api'
import type { AdminUser, UserRole } from '@/types'
import { useToast } from '@/store/toast'
import { useConfirm } from '@/store/confirm'
import { NeonButton } from '@/components/ui'
import { Search, Ban, UserCheck, Shield, ShieldOff, ChevronLeft, ChevronRight, Users, X, KeyRound, Bell, BellOff, Gift } from 'lucide-react'

export function AdminUsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [bannedOnly, setBannedOnly] = useState(false)
  const [page, setPage] = useState(0)
  const [banModalUser, setBanModalUser] = useState<AdminUser | null>(null)
  const [banReason, setBanReason] = useState('')
  const [banDuration, setBanDuration] = useState<string>('permanent')
  const [banCustomDate, setBanCustomDate] = useState('')
  const [banning, setBanning] = useState(false)
  const [resetPasswordUser, setResetPasswordUser] = useState<AdminUser | null>(null)
  const [newPassword, setNewPassword] = useState('')
  const [resettingPassword, setResettingPassword] = useState(false)

  const toast = useToast()
  const confirm = useConfirm()

  const LIMIT = 20

  const loadUsers = useCallback(async () => {
    setLoading(true)
    try {
      const data = await adminApi.listUsers(page * LIMIT, LIMIT, search || undefined, bannedOnly)
      setUsers(data)
    } catch (err) {
      console.error('Failed to load users:', err)
      toast.error('Ошибка загрузки пользователей')
    } finally {
      setLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, search, bannedOnly])

  useEffect(() => {
    loadUsers()
  }, [loadUsers])

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
    setPage(0)
    loadUsers()
  }

  const handleBan = async () => {
    if (!banModalUser || !banReason.trim()) return

    let bannedUntil: string | undefined
    if (banDuration !== 'permanent') {
      const now = new Date()
      if (banDuration === '1d') {
        now.setDate(now.getDate() + 1)
        bannedUntil = now.toISOString()
      } else if (banDuration === '7d') {
        now.setDate(now.getDate() + 7)
        bannedUntil = now.toISOString()
      } else if (banDuration === '30d') {
        now.setDate(now.getDate() + 30)
        bannedUntil = now.toISOString()
      } else if (banDuration === 'custom' && banCustomDate) {
        bannedUntil = new Date(banCustomDate).toISOString()
      }
    }

    setBanning(true)
    try {
      const updated = await adminApi.banUser(banModalUser.id, banReason, bannedUntil)
      setUsers(users.map(u => u.id === updated.id ? updated : u))
      toast.success(`Пользователь ${updated.nickname} заблокирован`)
      setBanModalUser(null)
      setBanReason('')
      setBanDuration('permanent')
      setBanCustomDate('')
    } catch (err) {
      console.error('Failed to ban user:', err)
      toast.error('Ошибка блокировки')
    } finally {
      setBanning(false)
    }
  }

  const handleUnban = async (user: AdminUser) => {
    const confirmed = await confirm({
      title: 'Разблокировать пользователя',
      message: `Вы уверены, что хотите разблокировать ${user.nickname}?`,
      confirmText: 'Разблокировать',
    })
    if (!confirmed) return

    try {
      const updated = await adminApi.unbanUser(user.id)
      setUsers(users.map(u => u.id === updated.id ? updated : u))
      toast.success(`Пользователь ${updated.nickname} разблокирован`)
    } catch (err) {
      console.error('Failed to unban user:', err)
      toast.error('Ошибка разблокировки')
    }
  }

  const handleRoleChange = async (user: AdminUser, newRole: UserRole) => {
    const confirmed = await confirm({
      title: 'Изменить роль',
      message: `Изменить роль ${user.nickname} на ${newRole === 'admin' ? 'Администратор' : 'Пользователь'}?`,
      confirmText: 'Изменить',
    })
    if (!confirmed) return

    try {
      const updated = await adminApi.setUserRole(user.id, newRole)
      setUsers(users.map(u => u.id === updated.id ? updated : u))
      toast.success(`Роль ${updated.nickname} изменена`)
    } catch (err) {
      console.error('Failed to change role:', err)
      toast.error('Ошибка изменения роли')
    }
  }

  const handleResetPassword = async () => {
    if (!resetPasswordUser || !newPassword.trim() || newPassword.length < 6) return

    setResettingPassword(true)
    try {
      const updated = await adminApi.resetUserPassword(resetPasswordUser.id, newPassword)
      setUsers(users.map(u => u.id === updated.id ? updated : u))
      toast.success(`Пароль ${updated.nickname} сброшен`)
      setResetPasswordUser(null)
      setNewPassword('')
    } catch (err) {
      console.error('Failed to reset password:', err)
      toast.error('Ошибка сброса пароля')
    } finally {
      setResettingPassword(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="p-2 rounded-lg bg-blue-500/20 border border-blue-500/30">
          <Users className="w-6 h-6 text-blue-400" />
        </div>
        <h1 className="text-2xl font-bold text-white">Пользователи</h1>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <form onSubmit={handleSearch} className="flex-1 flex gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <input
              type="text"
              placeholder="Поиск по логину или никнейму..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full bg-dark-700/50 border border-dark-600 rounded-xl pl-10 pr-4 py-2.5 text-white placeholder:text-gray-500 focus:outline-none focus:border-accent-500/50 focus:ring-1 focus:ring-accent-500/20 transition-all"
            />
          </div>
          <NeonButton type="submit" color="purple">
            Найти
          </NeonButton>
        </form>

        <label className="flex items-center gap-2 text-gray-300 cursor-pointer group">
          <input
            type="checkbox"
            checked={bannedOnly}
            onChange={(e) => {
              setBannedOnly(e.target.checked)
              setPage(0)
            }}
            className="w-4 h-4 rounded border-dark-600 bg-dark-700 text-accent-500 focus:ring-accent-500/50 focus:ring-offset-0"
          />
          <span className="group-hover:text-white transition-colors">Только заблокированные</span>
        </label>
      </div>

      {/* Users Table */}
      <div className="glass rounded-xl border border-dark-600 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-dark-700/50 border-b border-dark-600">
              <tr>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">ID</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Логин</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Никнейм</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Роль</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Telegram</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Марафоны</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Уведомления</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Статус</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Действия</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-dark-600">
              {loading ? (
                <tr>
                  <td colSpan={9} className="px-4 py-8 text-center">
                    <div className="animate-spin rounded-full h-6 w-6 border-2 border-accent-500 border-t-transparent mx-auto" />
                  </td>
                </tr>
              ) : users.length === 0 ? (
                <tr>
                  <td colSpan={9} className="px-4 py-8 text-center text-gray-400">
                    Пользователи не найдены
                  </td>
                </tr>
              ) : (
                users.map((user) => (
                  <tr key={user.id} className="hover:bg-dark-700/30 transition-colors">
                    <td className="px-4 py-3 text-sm text-gray-400 font-mono">{user.id}</td>
                    <td className="px-4 py-3 text-sm text-white">{user.login}</td>
                    <td className="px-4 py-3 text-sm text-white font-medium">{user.nickname}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg ${
                        user.role === 'admin'
                          ? 'bg-accent-500/20 text-accent-400 border border-accent-500/30'
                          : 'bg-dark-600/50 text-gray-400 border border-dark-500'
                      }`}>
                        {user.role === 'admin' && <Shield className="w-3 h-3" />}
                        {user.role === 'admin' ? 'Админ' : 'Пользователь'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-400">
                      {user.telegram_username ? (
                        <span className="text-neon-400">@{user.telegram_username}</span>
                      ) : (
                        <span className="text-gray-600">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-400">{user.marathons_count}</td>
                    <td className="px-4 py-3">
                      {user.telegram_id ? (
                        <div className="flex items-center gap-1" title={`События: ${user.notify_events ? 'вкл' : 'выкл'}, Споры: ${user.notify_disputes ? 'вкл' : 'выкл'}, Модерация: ${user.notify_moderation ? 'вкл' : 'выкл'}`}>
                          {user.notify_events && user.notify_disputes && user.notify_moderation ? (
                            <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-lg bg-green-500/20 text-green-400 border border-green-500/30">
                              <Bell className="w-3 h-3" />
                              Все
                            </span>
                          ) : !user.notify_events && !user.notify_disputes && !user.notify_moderation ? (
                            <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-lg bg-red-500/20 text-red-400 border border-red-500/30">
                              <BellOff className="w-3 h-3" />
                              Откл
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-lg bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">
                              <Bell className="w-3 h-3" />
                              Частично
                            </span>
                          )}
                        </div>
                      ) : (
                        <span className="text-gray-600">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {user.is_banned ? (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg bg-red-500/20 text-red-400 border border-red-500/30">
                          <Ban className="w-3 h-3" />
                          Заблокирован
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg bg-green-500/20 text-green-400 border border-green-500/30">
                          <UserCheck className="w-3 h-3" />
                          Активен
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        {user.is_banned ? (
                          <button
                            onClick={() => handleUnban(user)}
                            className="p-2 text-green-400 hover:bg-green-500/20 rounded-lg transition-colors"
                            title="Разблокировать"
                          >
                            <UserCheck className="w-4 h-4" />
                          </button>
                        ) : user.role !== 'admin' ? (
                          <button
                            onClick={() => setBanModalUser(user)}
                            className="p-2 text-red-400 hover:bg-red-500/20 rounded-lg transition-colors"
                            title="Заблокировать"
                          >
                            <Ban className="w-4 h-4" />
                          </button>
                        ) : null}

                        {user.role === 'admin' ? (
                          <button
                            onClick={() => handleRoleChange(user, 'user')}
                            className="p-2 text-orange-400 hover:bg-orange-500/20 rounded-lg transition-colors"
                            title="Снять права админа"
                          >
                            <ShieldOff className="w-4 h-4" />
                          </button>
                        ) : (
                          <button
                            onClick={() => handleRoleChange(user, 'admin')}
                            className="p-2 text-accent-400 hover:bg-accent-500/20 rounded-lg transition-colors"
                            title="Сделать админом"
                          >
                            <Shield className="w-4 h-4" />
                          </button>
                        )}

                        <button
                          onClick={() => setResetPasswordUser(user)}
                          className="p-2 text-yellow-400 hover:bg-yellow-500/20 rounded-lg transition-colors"
                          title="Сбросить пароль"
                        >
                          <KeyRound className="w-4 h-4" />
                        </button>

                        <Link
                          to={`/admin/users/${user.id}/grant-item`}
                          className="p-2 text-green-400 hover:bg-green-500/20 rounded-lg transition-colors"
                          title="Выдать предмет"
                        >
                          <Gift className="w-4 h-4" />
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between px-4 py-3 border-t border-dark-600">
          <button
            onClick={() => setPage(Math.max(0, page - 1))}
            disabled={page === 0}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors rounded-lg hover:bg-dark-600/50"
          >
            <ChevronLeft className="w-4 h-4" />
            Назад
          </button>
          <span className="text-sm text-gray-500">
            Страница <span className="text-white font-medium">{page + 1}</span>
          </span>
          <button
            onClick={() => setPage(page + 1)}
            disabled={users.length < LIMIT}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors rounded-lg hover:bg-dark-600/50"
          >
            Вперед
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Ban Modal */}
      {banModalUser && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="glass rounded-2xl p-6 max-w-md w-full mx-4 border border-dark-600 shadow-2xl">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                <Ban className="w-5 h-5 text-red-400" />
                Заблокировать {banModalUser.nickname}?
              </h3>
              <button
                onClick={() => {
                  setBanModalUser(null)
                  setBanReason('')
                  setBanDuration('permanent')
                  setBanCustomDate('')
                }}
                className="p-1.5 text-gray-400 hover:text-white rounded-lg hover:bg-dark-600/50 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Ban Duration */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Срок блокировки
              </label>
              <select
                value={banDuration}
                onChange={(e) => setBanDuration(e.target.value)}
                className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-accent-500/50 transition-colors"
              >
                <option value="permanent">Навсегда</option>
                <option value="1d">1 день</option>
                <option value="7d">7 дней</option>
                <option value="30d">30 дней</option>
                <option value="custom">Указать дату</option>
              </select>
            </div>

            {/* Custom Date */}
            {banDuration === 'custom' && (
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Разблокировать
                </label>
                <input
                  type="datetime-local"
                  value={banCustomDate}
                  onChange={(e) => setBanCustomDate(e.target.value)}
                  min={new Date().toISOString().slice(0, 16)}
                  className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-accent-500/50 transition-colors"
                />
              </div>
            )}

            {/* Reason */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Причина
              </label>
              <textarea
                value={banReason}
                onChange={(e) => setBanReason(e.target.value)}
                placeholder="Причина блокировки..."
                rows={3}
                className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white placeholder:text-gray-500 focus:outline-none focus:border-accent-500/50 transition-colors resize-none"
              />
            </div>

            <div className="flex gap-3 justify-end">
              <NeonButton
                variant="ghost"
                onClick={() => {
                  setBanModalUser(null)
                  setBanReason('')
                  setBanDuration('permanent')
                  setBanCustomDate('')
                }}
              >
                Отмена
              </NeonButton>
              <NeonButton
                variant="danger"
                onClick={handleBan}
                disabled={!banReason.trim() || banning || (banDuration === 'custom' && !banCustomDate)}
                isLoading={banning}
                icon={<Ban className="w-4 h-4" />}
              >
                Заблокировать
              </NeonButton>
            </div>
          </div>
        </div>
      )}

      {/* Reset Password Modal */}
      {resetPasswordUser && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="glass rounded-2xl p-6 max-w-md w-full mx-4 border border-dark-600 shadow-2xl">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                <KeyRound className="w-5 h-5 text-yellow-400" />
                Сбросить пароль {resetPasswordUser.nickname}
              </h3>
              <button
                onClick={() => {
                  setResetPasswordUser(null)
                  setNewPassword('')
                }}
                className="p-1.5 text-gray-400 hover:text-white rounded-lg hover:bg-dark-600/50 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Новый пароль
              </label>
              <input
                type="text"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="Минимум 6 символов"
                className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white placeholder:text-gray-500 focus:outline-none focus:border-accent-500/50 transition-colors"
              />
              {newPassword && newPassword.length < 6 && (
                <p className="mt-2 text-sm text-red-400">Пароль должен быть минимум 6 символов</p>
              )}
              {resetPasswordUser.telegram_id && (
                <p className="mt-2 text-sm text-gray-400">
                  Пользователь получит уведомление в Telegram о смене пароля
                </p>
              )}
            </div>

            <div className="flex gap-3 justify-end">
              <NeonButton
                variant="ghost"
                onClick={() => {
                  setResetPasswordUser(null)
                  setNewPassword('')
                }}
              >
                Отмена
              </NeonButton>
              <NeonButton
                color="neon"
                onClick={handleResetPassword}
                disabled={!newPassword.trim() || newPassword.length < 6 || resettingPassword}
                isLoading={resettingPassword}
                icon={<KeyRound className="w-4 h-4" />}
              >
                Сбросить
              </NeonButton>
            </div>
          </div>
        </div>
      )}

    </div>
  )
}
