'use client'

import useSWR from 'swr'
import { Building2, Users, Wifi, WifiOff, ListTodo, AlertTriangle, RefreshCw, CheckCircle2, Clock, Activity } from 'lucide-react'
import { useAuth } from '@/lib/auth-context'
import { AgentStatusBadge } from '@/components/ui/status-badge'
import { formatRelativeTime } from '@/lib/utils-ad'
import Link from 'next/link'
import { cn } from '@/lib/utils'
import { Skeleton } from '@/components/ui/skeleton'

const fetcher = (url: string) =>
  fetch(url).then((r) => r.json()).then((d) => (Array.isArray(d) ? d : d))

function MetricCard({
  icon: Icon,
  label,
  value,
  sub,
  color = 'primary',
  loading = false,
}: {
  icon: React.ElementType
  label: string
  value?: string | number
  sub?: string
  color?: 'primary' | 'green' | 'red' | 'yellow'
  loading?: boolean
}) {
  const colorMap = {
    primary: 'text-primary bg-primary/10',
    green: 'text-green-600 bg-green-100',
    red: 'text-red-600 bg-red-100',
    yellow: 'text-yellow-600 bg-yellow-100',
  }
  return (
    <div className="bg-card border border-border rounded-xl p-5 flex items-start gap-4">
      <div className={cn('w-10 h-10 rounded-lg flex items-center justify-center shrink-0', colorMap[color])}>
        <Icon className="w-5 h-5" />
      </div>
      <div>
        {loading ? (
          <>
            <Skeleton className="h-7 w-16 mb-1" />
            <Skeleton className="h-4 w-24" />
          </>
        ) : (
          <>
            <p className="text-2xl font-bold text-foreground">{value ?? 0}</p>
            <p className="text-sm font-medium text-foreground">{label}</p>
            {sub && <p className="text-xs text-muted-foreground mt-0.5">{sub}</p>}
          </>
        )}
      </div>
    </div>
  )
}

export default function DashboardPage() {
  const { user } = useAuth()
  const isAdmin = user?.role === 'admin_global'

  const { data, isLoading } = useSWR('/api/dashboard', fetcher, { refreshInterval: 30000 })

  const stats = data?.stats ?? {}
  const recentAudit = data?.recent_audit ?? []
  const recentTenants = data?.recent_tenants ?? []
  const lastSync = data?.last_sync ?? null
  const tenant = data?.tenant ?? null

  if (!isAdmin) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-xl font-bold text-foreground">{tenant?.name ?? user?.email}</h2>
          <p className="text-sm text-muted-foreground">Painel do tenant</p>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            icon={Wifi}
            label="Status do Conector"
            value={tenant?.agent_status === 'online' ? 'Online' : 'Offline'}
            sub={`Último contato: ${formatRelativeTime(tenant?.agent_last_seen ?? null)}`}
            color={tenant?.agent_status === 'online' ? 'green' : 'red'}
            loading={isLoading}
          />
          <MetricCard
            icon={Users}
            label="Usuários AD"
            value={stats.total_ad_users}
            sub={`${stats.enabled_ad_users ?? 0} habilitados`}
            color="primary"
            loading={isLoading}
          />
          <MetricCard
            icon={UsersRound}
            label="Grupos AD"
            value={stats.total_groups}
            loading={isLoading}
          />
          <MetricCard
            icon={AlertTriangle}
            label="Tarefas Pendentes"
            value={stats.pending_tasks}
            sub="Aguardando agente"
            color={stats.pending_tasks > 0 ? 'yellow' : 'green'}
            loading={isLoading}
          />
        </div>

        {lastSync && (
          <div className="bg-card border border-border rounded-xl p-4 flex items-center gap-3">
            <RefreshCw className="w-4 h-4 text-muted-foreground" />
            <div>
              <p className="text-sm font-medium text-foreground">Última sincronização</p>
              <p className="text-xs text-muted-foreground">
                {formatRelativeTime(lastSync.started_at)} &middot; Status: {lastSync.status}
              </p>
            </div>
          </div>
        )}

        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <div className="flex items-center justify-between px-5 py-4 border-b border-border">
            <h3 className="font-semibold text-foreground">Atividades recentes</h3>
            <Link href="/audit" className="text-xs text-primary hover:underline">Ver todas</Link>
          </div>
          <div className="divide-y divide-border">
            {isLoading ? (
              Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="px-5 py-3 flex items-center gap-3">
                  <Skeleton className="w-2 h-2 rounded-full" />
                  <Skeleton className="h-4 flex-1" />
                </div>
              ))
            ) : recentAudit.length === 0 ? (
              <p className="px-5 py-6 text-sm text-muted-foreground text-center">Nenhuma atividade registrada.</p>
            ) : recentAudit.map((log: any) => (
              <div key={log.id} className="px-5 py-3 flex items-start gap-3">
                <Activity className="w-3.5 h-3.5 mt-0.5 text-muted-foreground shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-foreground truncate">{log.action} — {log.object_name ?? '—'}</p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {log.user_name ?? '—'} &middot; {formatRelativeTime(log.created_at)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-foreground">Visão Geral</h2>
        <p className="text-sm text-muted-foreground">Bem-vindo ao painel de administração global.</p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <MetricCard
          icon={Building2}
          label="Empresas Ativas"
          value={stats.total_tenants}
          color="primary"
          loading={isLoading}
        />
        <MetricCard
          icon={Users}
          label="Usuários do Portal"
          value={stats.total_portal_users}
          color="primary"
          loading={isLoading}
        />
        <MetricCard
          icon={ListTodo}
          label="Tarefas Pendentes"
          value={stats.pending_tasks}
          color={stats.pending_tasks > 0 ? 'yellow' : 'green'}
          loading={isLoading}
        />
        <MetricCard
          icon={Activity}
          label="Eventos Hoje"
          value={stats.audit_today}
          color="primary"
          loading={isLoading}
        />
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <div className="flex items-center justify-between px-5 py-4 border-b border-border">
            <h3 className="font-semibold text-foreground">Empresas Recentes</h3>
            <Link href="/tenants" className="text-xs text-primary hover:underline">Ver todas</Link>
          </div>
          <div className="divide-y divide-border">
            {isLoading ? (
              Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="px-5 py-3 flex items-center gap-3">
                  <Skeleton className="h-4 flex-1" />
                  <Skeleton className="h-5 w-16" />
                </div>
              ))
            ) : recentTenants.length === 0 ? (
              <p className="px-5 py-6 text-sm text-muted-foreground text-center">Nenhuma empresa cadastrada.</p>
            ) : recentTenants.map((t: any) => (
              <div key={t.id} className="px-5 py-3 flex items-center gap-3">
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-foreground truncate">{t.name}</p>
                  <p className="text-xs text-muted-foreground">{t.domain}</p>
                </div>
                <AgentStatusBadge status={t.agent_status ?? 'offline'} />
              </div>
            ))}
          </div>
        </div>

        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <div className="flex items-center justify-between px-5 py-4 border-b border-border">
            <h3 className="font-semibold text-foreground">Auditoria Recente</h3>
            <Link href="/audit" className="text-xs text-primary hover:underline">Ver todas</Link>
          </div>
          <div className="divide-y divide-border">
            {isLoading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="px-5 py-3 flex items-center gap-3">
                  <Skeleton className="w-2 h-2 rounded-full" />
                  <Skeleton className="h-4 flex-1" />
                </div>
              ))
            ) : recentAudit.length === 0 ? (
              <p className="px-5 py-6 text-sm text-muted-foreground text-center">Nenhuma atividade registrada.</p>
            ) : recentAudit.map((log: any) => (
              <div key={log.id} className="px-5 py-3 flex items-start gap-3">
                <Activity className="w-3.5 h-3.5 mt-0.5 text-muted-foreground shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-foreground truncate">
                    {log.action} — {log.object_name ?? '—'}
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {log.tenant_name ?? 'Global'} &middot; {log.user_name ?? '—'} &middot; {formatRelativeTime(log.created_at)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}

function UsersRound(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M18 21a8 8 0 0 0-16 0" />
      <circle cx="10" cy="8" r="5" />
      <path d="M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3" />
    </svg>
  )
}
