import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  useNodeDetails,
  useNodePods,
  useNodeMetrics,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  Server,
  AlertCircle,
  RefreshCw,
  ArrowLeft,
  Globe,
  Cpu,
  Monitor,
  HardDrive,
  Clock,
  Tag,
  Copy,
  Info,
  Terminal as TerminalIcon,
  TrendingUp,
} from 'lucide-react';
import { TerminalComponent } from '@/components/ui/terminal';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  AreaChart,
  Area,
} from 'recharts';

export function NodeDetailsPage() {
  const { nodeName } = useParams<{ nodeName: string }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const {
    nodeDetails,
    loading,
    error,
    refetch: refetchNodeDetails,
  } = useNodeDetails(nodeName || '');
  const {
    podStats,
    loading: podsLoading,
    refetch: refetchPods,
  } = useNodePods(nodeName || '');
  const {
    metrics,
    loading: metricsLoading,
    refetch: refetchMetrics,
  } = useNodeMetrics(nodeName || '');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isTerminalOpen, setIsTerminalOpen] = useState(false);
  const [terminalCommand, setTerminalCommand] = useState<string>('');

  // Histórico de métricas para gráficos
  const [metricsHistory, setMetricsHistory] = useState<Array<{
    time: string;
    cpu: number;
    memory: number;
    timestamp: number;
  }>>([]);
  const maxHistoryPoints = 20; // Manter últimos 20 pontos (~1.5 min)
  const [isBootstrapping, setIsBootstrapping] = useState(true); // Bootstrap rápido inicial

  const copyToClipboard = async (text: string, label: string) => {
    try {
      await navigator.clipboard.writeText(text);
      showToast({
        title: `${label} Copiado!`,
        description: `${text} foi copiado para a área de transferência`,
        variant: 'success',
      });
    } catch (err) {
      showToast({
        title: 'Erro',
        description: `Não foi possível copiar ${label.toLowerCase()}`,
        variant: 'destructive',
      });
    }
  };

  const formatMemory = (memory: string) => {
    if (memory.endsWith('Ki')) {
      const value = parseInt(memory.replace('Ki', ''));
      return `${Math.round(value / 1024 / 1024)} GB`;
    }
    return memory;
  };

  const formatCpu = (cpu: string) => {
    if (cpu.endsWith('m')) {
      const value = parseInt(cpu.replace('m', ''));
      return `${value / 1000} cores`;
    }
    return `${cpu} cores`;
  };

  const getStatusBadge = (condition: any) => {
    const isTrue = condition.status === 'True';
    const isFalse = condition.status === 'False';

    switch (condition.type) {
      case 'Ready':
        return (
          <Badge
            variant={isTrue ? 'default' : 'destructive'}
            className={isTrue ? 'bg-green-500' : ''}
          >
            {isTrue ? 'Ready' : 'Not Ready'}
          </Badge>
        );
      case 'MemoryPressure':
        return (
          <Badge variant={isTrue ? 'destructive' : 'secondary'}>
            {isTrue ? 'Memory Pressure' : 'No Memory Pressure'}
          </Badge>
        );
      case 'DiskPressure':
        return (
          <Badge variant={isTrue ? 'destructive' : 'secondary'}>
            {isTrue ? 'Disk Pressure' : 'No Disk Pressure'}
          </Badge>
        );
      case 'PIDPressure':
        return (
          <Badge variant={isTrue ? 'destructive' : 'secondary'}>
            {isTrue ? 'PID Pressure' : 'No PID Pressure'}
          </Badge>
        );
      case 'NetworkUnavailable':
        return (
          <Badge variant={isTrue ? 'destructive' : 'secondary'}>
            {isTrue ? 'Network Issue' : 'Network OK'}
          </Badge>
        );
      default:
        return (
          <Badge variant="outline">
            {condition.type}: {condition.status}
          </Badge>
        );
    }
  };

  const getNodeAge = (creationTimestamp: string) => {
    const creationTime = new Date(creationTimestamp);
    const now = new Date();
    const diffMs = now.getTime() - creationTime.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      return `${diffHours}h`;
    }
    if (diffDays < 30) {
      return `${diffDays}d`;
    }
    const diffMonths = Math.floor(diffDays / 30);
    return `${diffMonths}mo`;
  };

  const getCpuUsagePercent = () => {
    if (!metrics?.cpuPercent) return 0;
    return parseInt(metrics.cpuPercent.replace('%', ''));
  };

  const getMemoryUsagePercent = () => {
    if (!metrics?.memoryPercent) return 0;
    return parseInt(metrics.memoryPercent.replace('%', ''));
  };

  const getPodsUsageCount = () => {
    return podStats?.running || 0;
  };

  const getPodsAvailable = () => {
    if (!nodeDetails?.capacity?.pods) return 0;
    const totalCapacity = parseInt(nodeDetails.capacity.pods || '0');
    const running = podStats?.running || 0;
    return totalCapacity - running;
  };

  const isHighCpuUsage = getCpuUsagePercent() > 70;
  const isHighMemoryUsage = getMemoryUsagePercent() > 70;
  const isHighPodsUsage = getPodsAvailable() < 30;

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      // Executar todas as atualizações em paralelo
      await Promise.all([
        refetchNodeDetails(),
        refetchPods(),
        refetchMetrics(),
      ]);
    } catch (error) {
      console.error('Erro na atualização:', error);
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleDebugNode = () => {
    setTerminalCommand(`kubectl debug node/${nodeName} -it --image=busybox`);
    setIsTerminalOpen(true);
  };

  const handleTestTerminal = () => {
    setTerminalCommand('interactive'); // Flag para terminal interativo
    setIsTerminalOpen(true);
  };

  const handleKubectlNodes = () => {
    setTerminalCommand('kubectl get nodes -o wide');
    setIsTerminalOpen(true);
  };

  const handleNodePods = () => {
    setTerminalCommand(
      `kubectl get pods --all-namespaces --field-selector spec.nodeName=${nodeName}`,
    );
    setIsTerminalOpen(true);
  };

  const handleKubectlTest = () => {
    setTerminalCommand('kubectl get nodes');
    setIsTerminalOpen(true);
  };

  const handleListPods = () => {
    setTerminalCommand(
      `kubectl get pods --all-namespaces --field-selector spec.nodeName=${nodeName} -o wide`,
    );
    setIsTerminalOpen(true);
  };

  const handleNodeSSH = () => {
    // Tentar SSH direto no node usando o IP interno
    const nodeIP = nodeDetails?.addresses?.internalIP;
    if (nodeIP) {
      setTerminalCommand(`ssh root@${nodeIP}`);
      setIsTerminalOpen(true);
    }
  };

  const handleExecSystemPod = () => {
    // Exec em um pod de sistema comum que deve ter acesso ao node
    setTerminalCommand(
      `kubectl exec -n kube-system deployment/local-path-provisioner -- /bin/sh`,
    );
    setIsTerminalOpen(true);
  };

  const handleExecCoreDNS = () => {
    // Exec no CoreDNS que tem ferramentas úteis
    setTerminalCommand(
      `kubectl exec -n kube-system deployment/coredns -- /bin/sh`,
    );
    setIsTerminalOpen(true);
  };

  const handleCleanupDebugPods = () => {
    // Limpar os pods de debug antigos
    setTerminalCommand(
      `kubectl delete pods -l job-name --field-selector status.phase=Succeeded && kubectl delete pods -l job-name --field-selector status.phase=Failed`,
    );
    setIsTerminalOpen(true);
  };

  // Coletar métricas quando atualizarem
  useEffect(() => {
    if (!metrics || metricsLoading) return;

    const cpuPercent = parseInt(metrics.cpuPercent?.replace('%', '') || '0');
    const memoryPercent = parseInt(metrics.memoryPercent?.replace('%', '') || '0');
    const now = new Date();
    const timeString = now.toLocaleTimeString('pt-BR', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });

    setMetricsHistory((prev) => {
      const newHistory = [
        ...prev,
        {
          time: timeString,
          cpu: cpuPercent,
          memory: memoryPercent,
          timestamp: now.getTime(),
        },
      ];

      // Desativar bootstrap após coletar pontos suficientes
      if (newHistory.length >= 5 && isBootstrapping) {
        setIsBootstrapping(false);
      }

      // Manter apenas os últimos N pontos
      return newHistory.slice(-maxHistoryPoints);
    });
  }, [metrics, metricsLoading, isBootstrapping]);

  // Bootstrap rápido: coleta inicial rápida de métricas (a cada 2s)
  useEffect(() => {
    if (!nodeName || !isBootstrapping) return;

    const interval = setInterval(() => {
      refetchMetrics();
    }, 2000); // 2 segundos durante bootstrap

    return () => clearInterval(interval);
  }, [nodeName, isBootstrapping, refetchMetrics]);

  // Atualizar métricas a cada 5 segundos (após bootstrap)
  useEffect(() => {
    if (!nodeName || isBootstrapping) return; // Pula durante bootstrap

    const interval = setInterval(() => {
      refetchMetrics();
    }, 5000);

    return () => clearInterval(interval);
  }, [nodeName, isBootstrapping, refetchMetrics]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin" />
        <span className="ml-2">Carregando detalhes do node...</span>
      </div>
    );
  }

  if (error || !nodeDetails) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div>
              <h1 className="text-3xl font-bold text-foreground">
                Detalhes do Node
              </h1>
              <p className="text-muted-foreground">
                Erro ao carregar informações do node {nodeName}
              </p>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" onClick={handleDebugNode}>
              <TerminalIcon className="h-4 w-4 mr-2" />
              Debug Node
            </Button>
          </div>
        </div>
        <Card className="border-red-200">
          <CardHeader>
            <CardTitle className="text-red-600 flex items-center">
              <AlertCircle className="h-5 w-5 mr-2" />
              Erro ao carregar node
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-500 mb-4">{error}</p>
            <Button onClick={refetch} variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar novamente
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground flex items-center">
              <Server className="h-8 w-8 mr-3 text-blue-600" />
              {nodeDetails.name}
            </h1>
            <p className="text-muted-foreground">
              Detalhes completos do node Kubernetes
            </p>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          <Button variant="outline" onClick={handleTestTerminal}>
            <TerminalIcon className="h-4 w-4 mr-2" />
            Teste Terminal
          </Button>
          <Button variant="outline" onClick={handleKubectlNodes}>
            <TerminalIcon className="h-4 w-4 mr-2" />
            Kubectl Nodes
          </Button>
          <Button variant="outline" onClick={handleNodePods}>
            <TerminalIcon className="h-4 w-4 mr-2" />
            Pods do Node
          </Button>
          <Button
            onClick={handleRefresh}
            variant="outline"
            disabled={isRefreshing}
          >
            <RefreshCw
              className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`}
            />
            {isRefreshing ? 'Atualizando...' : 'Atualizar'}
          </Button>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className={isHighCpuUsage ? 'border-red-200 bg-red-50/30' : ''}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle
              className={`text-sm font-medium ${isHighCpuUsage ? 'text-red-700' : ''}`}
            >
              CPU
            </CardTitle>
            <Cpu
              className={`h-4 w-4 ${isHighCpuUsage ? 'text-red-600' : 'text-green-600'}`}
            />
          </CardHeader>
          <CardContent>
            <div
              className={`text-2xl font-bold ${isHighCpuUsage ? 'text-red-800' : ''}`}
            >
              {formatCpu(nodeDetails.capacity?.cpu || '0')}
            </div>
            <div
              className={`text-xs ${isHighCpuUsage ? 'text-red-600' : 'text-muted-foreground'}`}
            >
              {metricsLoading ? (
                <div className="flex items-center">
                  <Loader2 className="h-3 w-3 animate-spin mr-1" />
                  Carregando...
                </div>
              ) : (
                `${metrics?.cpuPercent || '0%'} em uso`
              )}
            </div>
          </CardContent>
        </Card>

        <Card
          className={isHighMemoryUsage ? 'border-red-200 bg-red-50/30' : ''}
        >
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle
              className={`text-sm font-medium ${isHighMemoryUsage ? 'text-red-700' : ''}`}
            >
              Memória
            </CardTitle>
            <Monitor
              className={`h-4 w-4 ${isHighMemoryUsage ? 'text-red-600' : 'text-purple-600'}`}
            />
          </CardHeader>
          <CardContent>
            <div
              className={`text-2xl font-bold ${isHighMemoryUsage ? 'text-red-800' : ''}`}
            >
              {formatMemory(nodeDetails.capacity?.memory || '0Ki')}
            </div>
            <div
              className={`text-xs ${isHighMemoryUsage ? 'text-red-600' : 'text-muted-foreground'}`}
            >
              {metricsLoading ? (
                <div className="flex items-center">
                  <Loader2 className="h-3 w-3 animate-spin mr-1" />
                  Carregando...
                </div>
              ) : (
                `${metrics?.memoryPercent || '0%'} em uso`
              )}
            </div>
          </CardContent>
        </Card>

        <Card className={isHighPodsUsage ? 'border-red-200 bg-red-50/30' : ''}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle
              className={`text-sm font-medium ${isHighPodsUsage ? 'text-red-700' : ''}`}
            >
              Pods
            </CardTitle>
            <HardDrive
              className={`h-4 w-4 ${isHighPodsUsage ? 'text-red-600' : 'text-orange-600'}`}
            />
          </CardHeader>
          <CardContent>
            <div
              className={`text-2xl font-bold ${isHighPodsUsage ? 'text-red-800' : ''}`}
            >
              {podsLoading ? (
                <Loader2 className="h-6 w-6 animate-spin" />
              ) : (
                `${podStats?.running || 0}/${nodeDetails.capacity?.pods || '0'}`
              )}
            </div>
            <p
              className={`text-xs ${isHighPodsUsage ? 'text-red-600' : 'text-muted-foreground'}`}
            >
              {podsLoading
                ? 'Carregando...'
                : `${podStats?.running || 0} em uso, ${parseInt(nodeDetails.capacity?.pods || '0') - (podStats?.running || 0)} disponíveis`}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Uptime</CardTitle>
            <Clock className="h-4 w-4 text-cyan-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {Math.floor(
                (new Date().getTime() -
                  new Date(
                    nodeDetails.metadata?.creationTimestamp || '',
                  ).getTime()) /
                  (1000 * 60 * 60 * 24),
              )}{' '}
              dias
            </div>
            <p className="text-xs text-muted-foreground">
              Online desde{' '}
              {new Date(
                nodeDetails.metadata?.creationTimestamp || '',
              ).toLocaleDateString('pt-BR')}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Gráficos de Métricas em Tempo Real */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <TrendingUp className="h-5 w-5 mr-2" />
            Métricas em Tempo Real
          </CardTitle>
          <CardDescription>
            Utilização de CPU e Memória nos últimos {Math.floor((maxHistoryPoints * 5) / 60)} minutos (atualiza a cada 5s)
          </CardDescription>
        </CardHeader>
        <CardContent>
          {metricsHistory.length < 2 ? (
            <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
              <Loader2 className="h-8 w-8 animate-spin mb-4" />
              <p>Coletando dados para gráficos...</p>
              <p className="text-sm">({metricsHistory.length} de 2 pontos mínimos)</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Gráfico de CPU */}
              <div>
                <h3 className="text-sm font-semibold mb-3 flex items-center">
                  <Cpu className="h-4 w-4 mr-2 text-green-600" />
                  Utilização de CPU
                </h3>
                <ResponsiveContainer width="100%" height={250}>
                  <AreaChart data={metricsHistory}>
                    <defs>
                      <linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#10b981" stopOpacity={0.3}/>
                        <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" opacity={0.3} />
                    <XAxis
                      dataKey="time"
                      tick={{ fontSize: 11 }}
                      angle={-45}
                      textAnchor="end"
                      height={60}
                    />
                    <YAxis
                      domain={[0, 100]}
                      tick={{ fontSize: 11 }}
                      label={{ value: '%', angle: -90, position: 'insideLeft' }}
                    />
                    <Tooltip
                      contentStyle={{
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        border: 'none',
                        borderRadius: '4px',
                        color: 'white'
                      }}
                      formatter={(value: number) => [`${value}%`, 'CPU']}
                    />
                    <Area
                      type="monotone"
                      dataKey="cpu"
                      stroke="#10b981"
                      strokeWidth={2}
                      fill="url(#colorCpu)"
                      isAnimationActive={false}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>

              {/* Gráfico de Memória */}
              <div>
                <h3 className="text-sm font-semibold mb-3 flex items-center">
                  <Monitor className="h-4 w-4 mr-2 text-purple-600" />
                  Utilização de Memória
                </h3>
                <ResponsiveContainer width="100%" height={250}>
                  <AreaChart data={metricsHistory}>
                    <defs>
                      <linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#a855f7" stopOpacity={0.3}/>
                        <stop offset="95%" stopColor="#a855f7" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" opacity={0.3} />
                    <XAxis
                      dataKey="time"
                      tick={{ fontSize: 11 }}
                      angle={-45}
                      textAnchor="end"
                      height={60}
                    />
                    <YAxis
                      domain={[0, 100]}
                      tick={{ fontSize: 11 }}
                      label={{ value: '%', angle: -90, position: 'insideLeft' }}
                    />
                    <Tooltip
                      contentStyle={{
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        border: 'none',
                        borderRadius: '4px',
                        color: 'white'
                      }}
                      formatter={(value: number) => [`${value}%`, 'Memória']}
                    />
                    <Area
                      type="monotone"
                      dataKey="memory"
                      stroke="#a855f7"
                      strokeWidth={2}
                      fill="url(#colorMemory)"
                      isAnimationActive={false}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Node Information */}
        <Card>
          <CardHeader>
            <CardTitle>Informações do Sistema</CardTitle>
            <CardDescription>
              Dados básicos do sistema operacional e hardware
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  OS
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">{nodeDetails.operatingSystem}</span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Arquitetura
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">{nodeDetails.architecture}</span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Kernel
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">{nodeDetails.kernelVersion}</span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Runtime
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">
                    {nodeDetails.containerRuntimeVersion}
                  </span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Kubelet
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">{nodeDetails.kubeletVersion}</span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  KubeProxy
                </label>
                <div className="flex items-center space-x-2">
                  <span className="text-sm">
                    {nodeDetails.kubeProxyVersion}
                  </span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Network Information */}
        <Card>
          <CardHeader>
            <CardTitle>Informações de Rede</CardTitle>
            <CardDescription>
              Endereços IP e configurações de rede
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                IP Interno
              </label>
              <div className="flex items-center space-x-2">
                <Globe
                  className="h-4 w-4 cursor-pointer hover:text-blue-500 transition-colors"
                  onClick={() =>
                    copyToClipboard(
                      nodeDetails.addresses?.internalIP || '',
                      'IP Interno',
                    )
                  }
                  title="Clique para copiar"
                />
                <span className="text-sm font-mono">
                  {nodeDetails.addresses?.internalIP || 'N/A'}
                </span>
                <Copy
                  className="h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground"
                  onClick={() =>
                    copyToClipboard(
                      nodeDetails.addresses?.internalIP || '',
                      'IP Interno',
                    )
                  }
                />
              </div>
            </div>
            {nodeDetails.addresses?.externalIP && (
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  IP Externo
                </label>
                <div className="flex items-center space-x-2">
                  <Globe
                    className="h-4 w-4 cursor-pointer hover:text-blue-500 transition-colors"
                    onClick={() =>
                      copyToClipboard(
                        nodeDetails.addresses.externalIP,
                        'IP Externo',
                      )
                    }
                    title="Clique para copiar"
                  />
                  <span className="text-sm font-mono">
                    {nodeDetails.addresses.externalIP}
                  </span>
                  <Copy
                    className="h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground"
                    onClick={() =>
                      copyToClipboard(
                        nodeDetails.addresses.externalIP,
                        'IP Externo',
                      )
                    }
                  />
                </div>
              </div>
            )}
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Hostname
              </label>
              <div className="flex items-center space-x-2">
                <span className="text-sm font-mono">
                  {nodeDetails.addresses?.hostname || 'N/A'}
                </span>
                {nodeDetails.addresses?.hostname && (
                  <Copy
                    className="h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground"
                    onClick={() =>
                      copyToClipboard(
                        nodeDetails.addresses.hostname,
                        'Hostname',
                      )
                    }
                  />
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Node Conditions */}
      <Card>
        <CardHeader>
          <CardTitle>Status e Condições</CardTitle>
          <CardDescription>
            Estado atual do node e suas condições
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {nodeDetails.status?.conditions?.map(
              (condition: any, index: number) => (
                <div key={index} className="p-4 border rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-medium">{condition.type}</span>
                    {getStatusBadge(condition)}
                  </div>
                  {condition.message && (
                    <p className="text-xs text-muted-foreground">
                      {condition.message}
                    </p>
                  )}
                  <p className="text-xs text-muted-foreground mt-1">
                    Última transição:{' '}
                    {new Date(condition.lastTransitionTime).toLocaleString(
                      'pt-BR',
                    )}
                  </p>
                </div>
              ),
            )}
          </div>
        </CardContent>
      </Card>

      {/* Labels */}
      {Object.keys(nodeDetails.labels || {}).length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Tag className="h-5 w-5 mr-2" />
              Labels
            </CardTitle>
            <CardDescription>Labels aplicados ao node</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {Object.entries(nodeDetails.labels || {}).map(([key, value]) => (
                <div
                  key={key}
                  className="flex items-center justify-between p-2 bg-muted rounded"
                >
                  <span className="text-sm font-mono text-muted-foreground">
                    {key}
                  </span>
                  <div className="flex items-center space-x-2">
                    <span className="text-sm font-mono">{value as string}</span>
                    <Copy
                      className="h-3 w-3 cursor-pointer text-muted-foreground hover:text-foreground"
                      onClick={() =>
                        copyToClipboard(`${key}=${value}`, 'Label')
                      }
                    />
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Terminal Component */}
      <TerminalComponent
        isOpen={isTerminalOpen}
        onClose={() => {
          setIsTerminalOpen(false);
          setTerminalCommand('');
        }}
        title="Terminal Test"
        command={terminalCommand}
      />
    </div>
  );
}
