import React, { useEffect, useState, useCallback } from 'react'
import { useRouter } from 'next/router'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Users,
  Search,
  RefreshCw,
  Shield,
  ShieldOff,
  Smartphone,
  Calendar,
  Crown,
  UserCheck,
  UserX,
} from 'lucide-react'
import { useAuth } from '@/context/AuthContext'
import { api } from '@/services/chatApiService'
import { PageHeader, Card, Badge } from '@/components/ui'

interface AdminUser {
  id: string
  name: string
  email: string
  role: 'ADMIN' | 'USER'
  isActive: boolean
  planId: string | null
  trialEndsAt: string | null
  createdAt: string
  online: boolean
  _count: { instances: number }
}

function OnlineDot({ online }: { online: boolean }) {
  return (
    <span className="relative inline-flex items-center justify-center w-5 h-5">
      {online && (
        <span className="absolute inline-flex w-full h-full rounded-full bg-emerald-400 opacity-40 animate-ping" />
      )}
      <span
        className={`relative inline-flex w-2.5 h-2.5 rounded-full ${
          online ? 'bg-emerald-400' : 'bg-slate-600'
        }`}
      />
    </span>
  )
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' })
}

function trialDaysLeft(endsAt: string | null): number | null {
  if (!endsAt) return null
  return Math.max(0, Math.ceil((new Date(endsAt).getTime() - Date.now()) / 86_400_000))
}

export default function AdminUsersPage() {
  const { user, loading } = useAuth()
  const router = useRouter()
  const [users, setUsers] = useState<AdminUser[]>([])
  const [fetching, setFetching] = useState(false)
  const [search, setSearch] = useState('')
  const [togglingId, setTogglingId] = useState<string | null>(null)

  const fetchUsers = useCallback(async () => {
    setFetching(true)
    try {
      const { data } = await api.get('/api/admin/users')
      setUsers(data)
    } catch {
      // silencioso
    } finally {
      setFetching(false)
    }
  }, [])

  useEffect(() => {
    if (!loading && user?.role !== 'admin') router.replace('/inbox')
  }, [loading, user, router])

  useEffect(() => {
    if (user?.role !== 'admin') return
    fetchUsers()
    const id = setInterval(fetchUsers, 10_000)
    return () => clearInterval(id)
  }, [user, fetchUsers])

  const toggleActive = async (u: AdminUser) => {
    setTogglingId(u.id)
    try {
      await api.patch(`/api/admin/users/${u.id}/status`, { isActive: !u.isActive })
      setUsers((prev) => prev.map((x) => (x.id === u.id ? { ...x, isActive: !u.isActive } : x)))
    } catch {
      // silencioso
    } finally {
      setTogglingId(null)
    }
  }

  if (loading || user?.role !== 'admin') return null

  const filtered = users.filter(
    (u) =>
      u.name.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase()),
  )

  const onlineCount = users.filter((u) => u.online).length

  return (
    <div className="min-h-screen bg-surface p-6 lg:p-10 font-sans">
      <PageHeader
        icon={Users}
        title="Usuários"
        subtitle="Gerenciamento de tenants e presença em tempo real"
        actions={
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-emerald-500/10 border border-emerald-500/20">
              <span className="relative flex w-2 h-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                <span className="relative inline-flex rounded-full w-2 h-2 bg-emerald-400" />
              </span>
              <span className="text-xs font-bold text-emerald-400">
                {onlineCount} online
              </span>
            </div>
            <button
              onClick={fetchUsers}
              className="p-2 rounded-xl bg-white/5 border border-white/5 hover:border-brand-500/30 hover:text-brand-400 text-slate-400 transition-all"
            >
              <RefreshCw size={15} className={fetching ? 'animate-spin' : ''} />
            </button>
          </div>
        }
      />

      {/* Search */}
      <div className="mb-6 relative max-w-sm">
        <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none" />
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Buscar por nome ou e-mail..."
          className="w-full bg-white/[0.03] border border-white/5 rounded-xl pl-9 pr-4 py-2.5 text-sm text-slate-300 placeholder-slate-600 focus:outline-none focus:border-brand-500/40 focus:bg-white/[0.05] transition-all"
        />
      </div>

      <Card variant="glass" padding="p-0" className="rounded-3xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-white/5 text-left">
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Usuário</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Status</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Role</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Instâncias</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Trial</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Criado em</th>
                <th className="px-5 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Ações</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/[0.03]">
              <AnimatePresence initial={false}>
                {fetching && users.length === 0 ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <tr key={i}>
                      {Array.from({ length: 7 }).map((__, j) => (
                        <td key={j} className="px-5 py-4">
                          <div className="h-4 rounded bg-white/5 animate-pulse" />
                        </td>
                      ))}
                    </tr>
                  ))
                ) : filtered.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="px-5 py-12 text-center text-slate-600 text-xs uppercase tracking-widest font-bold">
                      Nenhum usuário encontrado
                    </td>
                  </tr>
                ) : (
                  filtered.map((u, i) => {
                    const days = trialDaysLeft(u.trialEndsAt)
                    return (
                      <motion.tr
                        key={u.id}
                        initial={{ opacity: 0, y: 6 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: i * 0.03 }}
                        className="hover:bg-white/[0.02] transition-colors"
                      >
                        {/* Usuário */}
                        <td className="px-5 py-4">
                          <div className="flex items-center gap-3">
                            <OnlineDot online={u.online} />
                            <div>
                              <p className="font-semibold text-white">{u.name}</p>
                              <p className="text-xs text-slate-500 font-mono">{u.email}</p>
                            </div>
                          </div>
                        </td>

                        {/* Status conta */}
                        <td className="px-5 py-4">
                          <Badge variant={u.isActive ? 'success' : 'error'} dot>
                            {u.isActive ? 'Ativo' : 'Inativo'}
                          </Badge>
                        </td>

                        {/* Role */}
                        <td className="px-5 py-4">
                          {u.role === 'ADMIN' ? (
                            <span className="inline-flex items-center gap-1.5 text-xs font-bold text-amber-400">
                              <Crown size={13} /> Admin
                            </span>
                          ) : (
                            <span className="text-xs text-slate-500 font-bold">User</span>
                          )}
                        </td>

                        {/* Instâncias */}
                        <td className="px-5 py-4">
                          <span className="inline-flex items-center gap-1.5 text-slate-300 font-mono text-xs">
                            <Smartphone size={13} className="text-slate-500" />
                            {u._count.instances}
                          </span>
                        </td>

                        {/* Trial */}
                        <td className="px-5 py-4">
                          {days === null ? (
                            <span className="text-xs text-slate-600">—</span>
                          ) : days === 0 ? (
                            <Badge variant="error">Expirado</Badge>
                          ) : days <= 3 ? (
                            <Badge variant="warning">{days}d restantes</Badge>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-xs text-slate-400">
                              <Calendar size={12} /> {days}d
                            </span>
                          )}
                        </td>

                        {/* Criado em */}
                        <td className="px-5 py-4 text-xs text-slate-500 font-mono">
                          {formatDate(u.createdAt)}
                        </td>

                        {/* Ações */}
                        <td className="px-5 py-4">
                          <button
                            onClick={() => toggleActive(u)}
                            disabled={togglingId === u.id || u.role === 'ADMIN'}
                            title={u.isActive ? 'Desativar usuário' : 'Ativar usuário'}
                            className={`p-2 rounded-xl border transition-all ${
                              u.role === 'ADMIN'
                                ? 'opacity-30 cursor-not-allowed border-white/5 text-slate-600'
                                : u.isActive
                                ? 'border-red-500/20 text-red-400 hover:bg-red-500/10'
                                : 'border-emerald-500/20 text-emerald-400 hover:bg-emerald-500/10'
                            }`}
                          >
                            {togglingId === u.id ? (
                              <RefreshCw size={14} className="animate-spin" />
                            ) : u.isActive ? (
                              <UserX size={14} />
                            ) : (
                              <UserCheck size={14} />
                            )}
                          </button>
                        </td>
                      </motion.tr>
                    )
                  })
                )}
              </AnimatePresence>
            </tbody>
          </table>
        </div>

        {users.length > 0 && (
          <div className="px-5 py-3 border-t border-white/5 flex items-center justify-between">
            <span className="text-xs text-slate-600">{filtered.length} de {users.length} usuários</span>
            <div className="flex items-center gap-4 text-xs text-slate-600">
              <span className="flex items-center gap-1.5"><Shield size={12} className="text-emerald-500" /> {users.filter(u => u.isActive).length} ativos</span>
              <span className="flex items-center gap-1.5"><ShieldOff size={12} className="text-red-500" /> {users.filter(u => !u.isActive).length} inativos</span>
            </div>
          </div>
        )}
      </Card>
    </div>
  )
}
