'use client'

import { use } from 'react'
import Link from 'next/link'
import { ArrowLeft, Settings, Cpu, RefreshCw, Users, Network } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { AgentStatusBadge, StatusBadge } from '@/components/ui/status-badge'
import { formatDate, formatRelativeTime } from '@/lib/utils-ad'
import { cn } from '@/lib/utils'
import useSWR from 'swr'

function fetcher(url: string) {
  const token = typeof window !== 'undefined' ? sessionStorage.getItem('adm_token') : null
  return fetch(url, {
    credentials: 'include',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  }).then((r) => r.ok ? r.json() : null)
}

export default function TenantDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)

  const { data: tenant } = useSWR(`/api/tenants/${id}`, fetcher)
  const { data: syncData } = useSWR(`/api/sync?tenant_id=${id}&limit=1`, (url: string) =>
    fetcher(url).then((d) => Array.isArray(d) ? d[0] : null)
  )
  const { data: auditData } = useSWR(`/api/audit?tenant_id=${id}&limit=6`, (url: string) =>
    fetcher(url).then((d) => d?.data ?? [])
  )

  const logs: any[] = auditData ?? []

  if (!tenant) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-muted-foreground">Carregando...</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/tenants">
          <Button variant="outline" size="sm">
            <ArrowLeft className="w-4 h-4 mr-2" />
            Voltar
          </Button>
        </Link>
        <div className="flex-1">
          <h2 className="text-xl font-bold text-foreground">{tenant.name}</h2>
          <p className="text-sm text-muted-foreground">{tenant.domain}</p>
        </div>
        <div className="flex items-center gap-2">
          <StatusBadge status={tenant.status} />
          <AgentStatusBadge status={tenant.agent_status ?? 'offline'} />
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-4">
          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <Network className="w-4 h-4 text-muted-foreground" />
              Configuracao do Active Directory
            </h3>
            <div className="grid grid-cols-2 gap-3 text-sm">
              {[
                { label: 'Dominio', value: tenant.domain },
                { label: 'Base DN', value: tenant.base_dn ?? '—' },
                { label: 'Sufixo UPN', value: tenant.upn_suffix ?? '—' },
                { label: 'Controlador de Dominio', value: tenant.preferred_dc ?? '—' },
                { label: 'Porta LDAP', value: String(tenant.ldap_port ?? 389) },
                { label: 'SSL/TLS', value: tenant.use_ssl ? 'Sim' : 'Nao' },
                { label: 'OU Usuarios', value: tenant.default_user_ou ?? '—' },
                { label: 'OU Grupos', value: tenant.default_group_ou ?? '—' },
                { label: 'Usuario tecnico', value: tenant.ad_service_user ?? '—' },
              ].map((f) => (
                <div key={f.label}>
                  <p className="text-xs font-semibold text-muted-foreground">{f.label}</p>
                  <p className="font-mono text-xs text-foreground mt-0.5 break-all">{f.value}</p>
                </div>
              ))}
            </div>
            <div className="flex gap-2 pt-2">
              <Button size="sm" variant="outline" asChild>
                <Link href={`/tenant-config?tenant=${tenant.id}`}>
                  <Settings className="w-4 h-4 mr-2" />Configurar
                </Link>
              </Button>
              <Button size="sm" variant="outline" asChild>
                <Link href={`/agent?tenant=${tenant.id}`}>
                  <Cpu className="w-4 h-4 mr-2" />Gerenciar Agente
                </Link>
              </Button>
            </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">
              {logs.length === 0 ? (
                <p className="px-5 py-6 text-sm text-center text-muted-foreground">Nenhuma atividade registrada.</p>
              ) : logs.map((log: any) => (
                <div key={log.id} className="px-5 py-3 flex items-start gap-3">
                  <span className={cn('mt-1 w-2 h-2 rounded-full shrink-0', log.status === 'success' ? 'bg-green-500' : 'bg-red-500')} />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-foreground">{log.details}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {log.user_name ?? log.userName} &middot; {formatRelativeTime(log.created_at ?? log.createdAt)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="space-y-4">
          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <Cpu className="w-4 h-4 text-muted-foreground" />
              Status do Agente
            </h3>
            <div className="space-y-3 text-sm">
              <div>
                <p className="text-xs text-muted-foreground">Status</p>
                <AgentStatusBadge status={tenant.agent_status ?? 'offline'} className="mt-1" />
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Hostname</p>
                <p className="font-mono text-foreground">{tenant.agent_hostname ?? '—'}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Versao</p>
                <p className="font-mono text-foreground">{tenant.agent_version ?? '—'}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Ultimo contato</p>
                <p className="text-foreground">{formatRelativeTime(tenant.last_heartbeat)}</p>
                {tenant.last_heartbeat && (
                  <p className="text-xs text-muted-foreground">{formatDate(tenant.last_heartbeat)}</p>
                )}
              </div>
            </div>
            <Button size="sm" className="w-full" asChild>
              <Link href={`/agent-download?tenant=${tenant.id}`}>
                Download do Agente
              </Link>
            </Button>
          </div>

          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <RefreshCw className="w-4 h-4 text-muted-foreground" />
              Sincronizacao
            </h3>
            {syncData ? (
              <div className="space-y-3 text-sm">
                <div>
                  <p className="text-xs text-muted-foreground">Ultima sinc. completa</p>
                  <p className="text-foreground">{formatRelativeTime(syncData.started_at)}</p>
                </div>
                <div className="flex items-center gap-4">
                  <div>
                    <p className="text-xs text-muted-foreground">Usuarios</p>
                    <p className="font-bold text-foreground">{syncData.users_synced ?? 0}</p>
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground">Grupos</p>
                    <p className="font-bold text-foreground">{syncData.groups_synced ?? 0}</p>
                  </div>
                </div>
                {syncData.error_message && (
                  <p className="text-xs text-destructive bg-destructive/10 rounded-md p-2">
                    {syncData.error_message}
                  </p>
                )}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">Sem dados de sincronizacao.</p>
            )}
            <Button size="sm" variant="outline" className="w-full" asChild>
              <Link href={`/sync?tenant=${tenant.id}`}>
                <RefreshCw className="w-4 h-4 mr-2" />Sincronizar agora
              </Link>
            </Button>
          </div>

          <div className="bg-card border border-border rounded-xl p-5 space-y-3">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <Users className="w-4 h-4 text-muted-foreground" />
              Estatisticas
            </h3>
            {[
              { label: 'Usuarios AD', value: tenant.users_count ?? 0 },
              { label: 'Grupos AD', value: tenant.groups_count ?? 0 },
            ].map((s) => (
              <div key={s.label} className="flex items-center justify-between">
                <p className="text-sm text-muted-foreground">{s.label}</p>
                <p className="text-sm font-bold text-foreground">{s.value}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
