'use client'

import { useState } from 'react'
import {
  Cpu,
  KeyRound,
  RotateCcw,
  ShieldOff,
  Activity,
  Clock,
  Server,
  AlertTriangle,
  Download,
  Terminal,
  CheckCircle2,
  Copy,
  ChevronDown,
  ChevronRight,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { AgentStatusBadge } from '@/components/ui/status-badge'
import useSWR from 'swr'
import { useAuth } from '@/lib/auth-context'
import { formatDate, formatRelativeTime } from '@/lib/utils-ad'
import { TaskStatusBadge } from '@/components/ui/status-badge'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { cn } from '@/lib/utils'
import { apiFetch } from '@/lib/fetcher'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'

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

function CopyButton({ value }: { value: string }) {
  const [copied, setCopied] = useState(false)
  function copy() {
    navigator.clipboard.writeText(value)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }
  return (
    <button
      onClick={copy}
      className="text-muted-foreground hover:text-foreground transition-colors"
      title="Copiar"
    >
      {copied ? <CheckCircle2 className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}
    </button>
  )
}

function CodeBlock({ code, label }: { code: string; label?: string }) {
  return (
    <div className="rounded-lg border border-border overflow-hidden">
      {label && (
        <div className="flex items-center justify-between px-3 py-1.5 bg-muted border-b border-border">
          <span className="text-xs text-muted-foreground font-mono">{label}</span>
          <CopyButton value={code} />
        </div>
      )}
      <pre className="p-3 text-xs font-mono text-foreground bg-muted/50 overflow-x-auto whitespace-pre-wrap break-all leading-relaxed">
        {code}
      </pre>
    </div>
  )
}

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

  const { data: tenants = [] } = useSWR(
    isAdmin ? '/api/tenants' : null,
    fetcher,
  )

  const [selectedTenantId, setSelectedTenantId] = useState('')
  const [showTokenModal, setShowTokenModal] = useState(false)
  const [generatedToken, setGeneratedToken] = useState('')
  const [revokeConfirm, setRevokeConfirm] = useState(false)
  const [generatingToken, setGeneratingToken] = useState(false)

  // Para tenant_admin usa o próprio tenant; admin_global usa o selecionado
  const effectiveTenantId = isAdmin
    ? selectedTenantId || (tenants[0] ? String(tenants[0].id) : '')
    : user?.tenantId ?? ''

  const { data: agentData, mutate: mutateAgent } = useSWR(
    effectiveTenantId ? `/api/agent?tenant_id=${effectiveTenantId}` : null,
    fetcher,
    { refreshInterval: 15000 },
  )
  const { data: tasksData = [] } = useSWR(
    effectiveTenantId ? `/api/agent/tasks?tenant_id=${effectiveTenantId}` : null,
    fetcher,
    { refreshInterval: 10000 },
  )

  const tenant = agentData ?? null
  const tasks = Array.isArray(tasksData) ? tasksData : []
  const agentToken = tenant?.agent_token ?? ''
  const portalEndpoint = 'https://servicosonline.consultarti.tec.br/api/agent'

  async function generateToken() {
    setGeneratingToken(true)
    try {
      const res = await apiFetch('/api/agent', {
        method: 'POST',
        body: JSON.stringify({ tenant_id: effectiveTenantId, action: 'generate_token' }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error ?? 'Erro ao gerar token')
      setGeneratedToken(data.token ?? '')
      setShowTokenModal(true)
      mutateAgent()
    } catch (err: any) {
      alert('Erro ao gerar token: ' + err.message)
    } finally {
      setGeneratingToken(false)
    }
  }

  async function revokeToken() {
    await apiFetch('/api/agent', {
      method: 'POST',
      body: JSON.stringify({ tenant_id: effectiveTenantId, action: 'revoke_token' }),
    })
    mutateAgent()
    setRevokeConfirm(false)
  }

  // Script gerado automaticamente com token e tenant preenchidos
  function buildInstallScript(token: string) {
    return `irm "${portalEndpoint}/install" | iex -Token "${token}" -TenantId "${effectiveTenantId}"`
  }

  const psUninstall = `$ServiceName = "ConsultarTIAgent"
Stop-Service -Name $ServiceName -Force
Remove-Service -Name $ServiceName
Remove-Item -Recurse -Force "C:\\ConsultarTI\\Agent"`

  const psUpdateToken = (token: string) =>
    `Stop-Service ConsultarTIAgent; [Environment]::SetEnvironmentVariable("CTAPT_TOKEN","${token}","Machine"); Start-Service ConsultarTIAgent`

  if (!effectiveTenantId) return (
    <div className="text-center py-20 text-muted-foreground">Nenhum tenant cadastrado.</div>
  )

  return (
    <div className="space-y-6">

      {/* Cabeçalho */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-foreground">Conector / Agente</h2>
          <p className="text-sm text-muted-foreground">
            Gerencie e instale o agente no servidor Active Directory da empresa.
          </p>
        </div>
        {isAdmin && (
          <Select value={selectedTenantId} onValueChange={setSelectedTenantId}>
            <SelectTrigger className="w-64">
              <SelectValue placeholder="Selecione a empresa..." />
            </SelectTrigger>
            <SelectContent>
              {(Array.isArray(tenants) ? tenants : []).map((t: any) => (
                <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      </div>

      <div className="grid lg:grid-cols-3 gap-6">

        {/* Coluna esquerda: status + ações */}
        <div className="lg:col-span-1 space-y-4">

          {/* Card de status */}
          <div className="bg-card border border-border rounded-xl p-5 space-y-5">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold text-foreground flex items-center gap-2">
                <Cpu className="w-4 h-4 text-muted-foreground" />
                Status do Agente
              </h3>
              <AgentStatusBadge status={tenant?.agent_status ?? 'offline'} />
            </div>

            <div className="space-y-3">
              <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/30">
                <Server className="w-4 h-4 text-muted-foreground shrink-0" />
                <div>
                  <p className="text-xs text-muted-foreground">Hostname</p>
                  <p className="text-sm font-mono text-foreground">{tenant?.agent_hostname ?? '—'}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/30">
                <Activity className="w-4 h-4 text-muted-foreground shrink-0" />
                <div>
                  <p className="text-xs text-muted-foreground">Versão</p>
                  <p className="text-sm font-mono text-foreground">{tenant?.agent_version ?? '—'}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/30">
                <Clock className="w-4 h-4 text-muted-foreground shrink-0" />
                <div>
                  <p className="text-xs text-muted-foreground">Último heartbeat</p>
                  <p className="text-sm text-foreground">{formatRelativeTime(tenant?.last_heartbeat)}</p>
                  {tenant?.last_heartbeat && (
                    <p className="text-xs text-muted-foreground">{formatDate(tenant.last_heartbeat)}</p>
                  )}
                </div>
              </div>
            </div>

            {/* Ações de token */}
            <div className="pt-2 border-t border-border">
              <Button
                variant="outline"
                className="w-full"
                size="sm"
                onClick={() => setRevokeConfirm(true)}
                disabled={!agentToken}
              >
                <ShieldOff className="w-4 h-4 mr-2" />
                Revogar Token Atual
              </Button>
            </div>
          </div>

          {/* Aviso offline */}
          {(tenant?.agent_status ?? 'offline') !== 'online' && (
            <div className="flex items-start gap-3 p-4 rounded-xl bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800">
              <AlertTriangle className="w-4 h-4 text-yellow-600 shrink-0 mt-0.5" />
              <div>
                <p className="text-sm font-medium text-yellow-800 dark:text-yellow-400">
                  Agente offline
                </p>
                <p className="text-xs text-yellow-700 dark:text-yellow-500 mt-1">
                  Nenhum agente conectado. Siga as instruções de instalação ao lado para configurar o conector no servidor AD.
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Coluna direita: tabs de instalação + tarefas */}
        <div className="lg:col-span-2 space-y-4">
          <Tabs defaultValue="install">
            <TabsList className="w-full">
              <TabsTrigger value="install" className="flex-1">
                <Download className="w-3.5 h-3.5 mr-2" />
                Instalação
              </TabsTrigger>
              <TabsTrigger value="tasks" className="flex-1">
                <Terminal className="w-3.5 h-3.5 mr-2" />
                Tarefas Recentes
              </TabsTrigger>
              <TabsTrigger value="settings" className="flex-1">
                <Cpu className="w-3.5 h-3.5 mr-2" />
                Configurações
              </TabsTrigger>
            </TabsList>

            {/* Aba de Instalação */}
            <TabsContent value="install" className="mt-4">
              <div className="bg-card border border-border rounded-xl divide-y divide-border">

                {/* Passo 1 */}
                <div className="p-5 flex gap-4">
                  <span className="flex items-center justify-center w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold shrink-0 mt-0.5">1</span>
                  <div className="flex-1 space-y-2">
                    <p className="font-semibold text-foreground text-sm">Gere o token de acesso</p>
                    <p className="text-sm text-muted-foreground">
                      Clique no botão abaixo para gerar um token. O comando de instalação será montado automaticamente com ele.
                    </p>
                    <Button size="sm" onClick={generateToken} disabled={generatingToken}>
                      <KeyRound className="w-3.5 h-3.5 mr-2" />
                      {generatingToken ? 'Gerando...' : generatedToken ? 'Gerar Novo Token' : 'Gerar Token de Instalação'}
                    </Button>
                  </div>
                </div>

                {/* Passo 2 */}
                <div className={cn('p-5 flex gap-4 transition-opacity', !generatedToken && 'opacity-40 pointer-events-none')}>
                  <span className="flex items-center justify-center w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold shrink-0 mt-0.5">2</span>
                  <div className="flex-1 space-y-3">
                    <p className="font-semibold text-foreground text-sm">Execute no servidor AD</p>
                    <p className="text-sm text-muted-foreground">
                      Abra o <strong>PowerShell como Administrador</strong> no servidor do Active Directory e cole o comando abaixo. Ele baixa e instala o agente automaticamente.
                    </p>
                    {generatedToken ? (
                      <CodeBlock
                        code={buildInstallScript(generatedToken)}
                        label="PowerShell — cole e execute como Administrador"
                      />
                    ) : (
                      <div className="rounded-lg border border-dashed border-border p-4 text-center text-xs text-muted-foreground">
                        Gere o token no passo 1 para ver o comando
                      </div>
                    )}
                    <div className="flex flex-wrap gap-4 text-xs text-muted-foreground pt-1">
                      {[
                        { icon: Server, text: 'Windows Server 2016+' },
                        { icon: Terminal, text: 'PowerShell 5.1+' },
                        { icon: Activity, text: 'Saída HTTPS porta 443' },
                      ].map(({ icon: Icon, text }) => (
                        <span key={text} className="flex items-center gap-1.5">
                          <Icon className="w-3.5 h-3.5" />
                          {text}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Passo 3 */}
                <div className={cn('p-5 flex gap-4 transition-opacity', !generatedToken && 'opacity-40')}>
                  <span className="flex items-center justify-center w-7 h-7 rounded-full bg-primary text-primary-foreground text-xs font-bold shrink-0 mt-0.5">3</span>
                  <div className="flex-1 space-y-2">
                    <p className="font-semibold text-foreground text-sm">Aguarde a conexão</p>
                    <p className="text-sm text-muted-foreground">
                      Após executar o script, o agente se registra automaticamente. O status no painel ao lado mudará para <strong>Online</strong> em até 60 segundos.
                    </p>
                  </div>
                </div>

                {/* Desinstalar (colapsável) */}
                <details className="group">
                  <summary className="flex items-center gap-2 cursor-pointer text-sm text-muted-foreground hover:text-foreground px-5 py-4 list-none transition-colors">
                    <ChevronRight className="w-3.5 h-3.5 group-open:hidden shrink-0" />
                    <ChevronDown className="w-3.5 h-3.5 hidden group-open:block shrink-0" />
                    Desinstalar o agente
                  </summary>
                  <div className="px-5 pb-5">
                    <CodeBlock code={psUninstall} label="PowerShell — Desinstalação" />
                  </div>
                </details>
              </div>
            </TabsContent>

            {/* Aba de Tarefas */}
            <TabsContent value="tasks" className="mt-4">
              <div className="bg-card border border-border rounded-xl overflow-hidden">
                <div className="px-5 py-4 border-b border-border">
                  <h3 className="font-semibold text-foreground">Tarefas Recentes</h3>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    Histórico de execução das tarefas enviadas ao agente.
                  </p>
                </div>
                <div className="divide-y divide-border">
                  {tasks.length === 0 ? (
                    <p className="px-5 py-10 text-center text-sm text-muted-foreground">
                      Nenhuma tarefa registrada para este tenant.
                    </p>
                  ) : tasks.map((task: any) => (
                    <div key={task.id} className="px-5 py-4">
                      <div className="flex items-start justify-between gap-3">
                        <div className="flex items-start gap-3">
                          <span className={cn(
                            'mt-1.5 w-2 h-2 rounded-full shrink-0',
                            task.status === 'success' ? 'bg-green-500' :
                            task.status === 'error' ? 'bg-red-500' :
                            task.status === 'pending' ? 'bg-yellow-500' : 'bg-blue-500',
                          )} />
                          <div>
                            <p className="text-sm font-medium text-foreground">{task.type}</p>
                            <p className="text-xs text-muted-foreground font-mono mt-0.5">#{task.id}</p>
                            {task.error_message && (
                              <p className="text-xs text-destructive mt-1">{task.error_message}</p>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          <TaskStatusBadge status={task.status} />
                          <span className="text-xs text-muted-foreground">
                            {formatRelativeTime(task.created_at)}
                          </span>
                        </div>
                      </div>
                      {task.completed_at && (
                        <p className="text-xs text-muted-foreground mt-2 ml-5">
                          Concluído em: {formatDate(task.completed_at)}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </TabsContent>

            {/* Aba de Configurações */}
            <TabsContent value="settings" className="mt-4">
              <div className="bg-card border border-border rounded-xl p-5 space-y-4">
                <h3 className="font-semibold text-foreground">Parâmetros do Agente</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { label: 'Intervalo de polling', value: '60 segundos' },
                    { label: 'Timeout de tarefa', value: '120 segundos' },
                    { label: 'Autenticação', value: 'Bearer Token (JWT)' },
                    { label: 'Protocolo', value: 'HTTPS / TLS 1.2+' },
                    { label: 'Porta de saída', value: '443 (HTTPS)' },
                    { label: 'Direção', value: 'Apenas saída (outbound)' },
                  ].map((c) => (
                    <div key={c.label} className="bg-muted/30 rounded-lg p-3">
                      <p className="text-xs text-muted-foreground">{c.label}</p>
                      <p className="text-sm font-medium text-foreground mt-0.5">{c.value}</p>
                    </div>
                  ))}
                </div>
                <div className="p-4 rounded-lg bg-muted/40 border border-border space-y-2 mt-2">
                  <p className="text-xs font-semibold text-foreground">Variáveis de ambiente (serviço Windows)</p>
                  <div className="space-y-1 font-mono text-xs text-muted-foreground">
                    <p><span className="text-foreground">CTAPT_PORTAL_URL</span> — URL do endpoint do portal</p>
                    <p><span className="text-foreground">CTAPT_TENANT_ID</span> — ID único da empresa</p>
                    <p><span className="text-foreground">CTAPT_TOKEN</span> — Token de autenticação gerado no portal</p>
                    <p><span className="text-foreground">CTAPT_POLL_INTERVAL</span> — Intervalo de polling em segundos (padrão: 60)</p>
                    <p><span className="text-foreground">CTAPT_LOG_LEVEL</span> — Nível de log: info | debug | error</p>
                  </div>
                </div>
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </div>

      {/* Modal token gerado */}
      <Dialog open={showTokenModal} onOpenChange={setShowTokenModal}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5 text-green-500" />
              Token gerado — copie o comando
            </DialogTitle>
            <DialogDescription>
              O comando abaixo já contém o token e o ID da empresa. Cole no PowerShell do servidor AD.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div className="flex items-start gap-2 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800">
              <AlertTriangle className="w-4 h-4 text-yellow-600 shrink-0 mt-0.5" />
              <p className="text-xs text-yellow-800 dark:text-yellow-400">
                Este token não será exibido novamente. Copie o comando abaixo antes de fechar.
              </p>
            </div>
            <CodeBlock
              code={buildInstallScript(generatedToken)}
              label="PowerShell — cole e execute como Administrador"
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => navigator.clipboard.writeText(buildInstallScript(generatedToken))}>
              <Copy className="w-3.5 h-3.5 mr-2" />
              Copiar comando
            </Button>
            <Button onClick={() => setShowTokenModal(false)}>Pronto</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Modal revogar */}
      <Dialog open={revokeConfirm} onOpenChange={setRevokeConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-destructive">
              <ShieldOff className="w-5 h-5" />
              Revogar Token do Agente
            </DialogTitle>
            <DialogDescription>
              O token atual será invalidado e o agente perderá acesso imediatamente.
            </DialogDescription>
          </DialogHeader>
          <p className="text-sm text-muted-foreground">
            Será necessário gerar um novo token e atualizar a variável de ambiente
            <strong> CTAPT_TOKEN</strong> no servidor, depois reiniciar o serviço
            <strong> ConsultarTIAgent</strong>.
          </p>
          <DialogFooter>
            <Button variant="outline" onClick={() => setRevokeConfirm(false)}>Cancelar</Button>
            <Button variant="destructive" onClick={revokeToken}>Confirmar Revogação</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
