import { useState, useEffect, useCallback } from 'react'
import { adminApi } from '@/api'
import type { AdminLog } from '@/types'
import { useToast } from '@/store/toast'
import { ChevronLeft, ChevronRight, Filter, ScrollText } from 'lucide-react'

const ACTION_LABELS: Record<string, string> = {
  user_ban: 'Бан пользователя',
  user_unban: 'Разбан пользователя',
  user_auto_unban: 'Авто-разбан (система)',
  user_role_change: 'Изменение роли',
  marathon_force_finish: 'Принудительное завершение',
  marathon_delete: 'Удаление марафона',
  content_update: 'Обновление контента',
  broadcast_all: 'Рассылка всем',
  broadcast_marathon: 'Рассылка марафону',
  admin_login: 'Вход админа',
  admin_2fa_success: '2FA успех',
  admin_2fa_fail: '2FA неудача',
}

const ACTION_COLORS: Record<string, string> = {
  user_ban: 'bg-red-500/20 text-red-400 border border-red-500/30',
  user_unban: 'bg-green-500/20 text-green-400 border border-green-500/30',
  user_auto_unban: 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30',
  user_role_change: 'bg-accent-500/20 text-accent-400 border border-accent-500/30',
  marathon_force_finish: 'bg-orange-500/20 text-orange-400 border border-orange-500/30',
  marathon_delete: 'bg-red-500/20 text-red-400 border border-red-500/30',
  content_update: 'bg-neon-500/20 text-neon-400 border border-neon-500/30',
  broadcast_all: 'bg-pink-500/20 text-pink-400 border border-pink-500/30',
  broadcast_marathon: 'bg-pink-500/20 text-pink-400 border border-pink-500/30',
  admin_login: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
  admin_2fa_success: 'bg-green-500/20 text-green-400 border border-green-500/30',
  admin_2fa_fail: 'bg-red-500/20 text-red-400 border border-red-500/30',
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

export function AdminLogsPage() {
  const [logs, setLogs] = useState<AdminLog[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [actionFilter, setActionFilter] = useState<string>('')
  const [page, setPage] = useState(0)

  const toast = useToast()

  const LIMIT = 30

  const loadLogs = useCallback(async () => {
    setLoading(true)
    try {
      const data = await adminApi.getLogs(page * LIMIT, LIMIT, actionFilter || undefined)
      setLogs(data.logs)
      setTotal(data.total)
    } catch (err) {
      console.error('Failed to load logs:', err)
      toast.error('Ошибка загрузки логов')
    } finally {
      setLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, actionFilter])

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

  const totalPages = Math.ceil(total / LIMIT)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-orange-500/20 border border-orange-500/30">
            <ScrollText className="w-6 h-6 text-orange-400" />
          </div>
          <h1 className="text-2xl font-bold text-white">Логи действий</h1>
        </div>
        <span className="text-sm text-gray-400 bg-dark-700/50 px-3 py-1.5 rounded-lg border border-dark-600">
          Всего: <span className="text-white font-medium">{total}</span> записей
        </span>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-4">
        <div className="flex items-center gap-3">
          <Filter className="w-5 h-5 text-gray-500" />
          <select
            value={actionFilter}
            onChange={(e) => {
              setActionFilter(e.target.value)
              setPage(0)
            }}
            className="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 min-w-[200px]"
          >
            <option value="">Все действия</option>
            {Object.entries(ACTION_LABELS).map(([value, label]) => (
              <option key={value} value={value}>{label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Logs 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">Дата</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>
                <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">IP</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-dark-600">
              {loading ? (
                <tr>
                  <td colSpan={6} 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>
              ) : logs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-8 text-center text-gray-400">
                    Логи не найдены
                  </td>
                </tr>
              ) : (
                logs.map((log) => (
                  <tr key={log.id} className="hover:bg-dark-700/30 transition-colors">
                    <td className="px-4 py-3 text-sm text-gray-400 whitespace-nowrap font-mono">
                      {formatDate(log.created_at)}
                    </td>
                    <td className="px-4 py-3 text-sm font-medium">
                      {log.admin_nickname ? (
                        <span className="text-white">{log.admin_nickname}</span>
                      ) : (
                        <span className="text-cyan-400 italic">Система</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2.5 py-1 text-xs font-medium rounded-lg ${ACTION_COLORS[log.action] || 'bg-dark-600/50 text-gray-400 border border-dark-500'}`}>
                        {ACTION_LABELS[log.action] || log.action}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-400">
                      <span className="text-gray-500">{log.target_type}</span>
                      <span className="text-neon-400 font-mono ml-1">#{log.target_id}</span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500 max-w-xs">
                      {log.details ? (
                        <span className="font-mono text-xs bg-dark-700/50 px-2 py-1 rounded truncate block">
                          {JSON.stringify(log.details)}
                        </span>
                      ) : (
                        <span className="text-gray-600">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500 font-mono">
                      {log.ip_address || '—'}
                    </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 className="text-white font-medium">{totalPages || 1}</span>
          </span>
          <button
            onClick={() => setPage(page + 1)}
            disabled={page >= totalPages - 1}
            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>
    </div>
  )
}
