import React, { useState, useEffect } 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { LogsModal } from '@/components/ui/logs-modal';
import { YamlEditor } from '@/components/ui/yaml-editor';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useDeploymentDetails, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  ArrowLeft,
  RefreshCw,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Container,
  Layers,
  Activity,
  AlertTriangle,
  Info,
  Play,
  Pause,
  RotateCcw,
  ArrowUpDown,
  Plus,
  Minus,
  ChevronDown,
  ChevronUp,
  Settings,
  Terminal,
  FileText,
  Zap,
  Shield,
  Database,
  Network,
  Eye,
  AlertCircle,
  Tag,
  Gauge,
  Copy,
  MoreVertical,
  Trash2,
  Brush,
  Download,
  Search,
  Filter,
  X,
  Highlighter,
  RotateCw,
  Square,
  Maximize2,
  Minimize2,
  Edit,
  Save,
  Trash,
  Edit3,
  Check,
} from 'lucide-react';

export function DeploymentDetailsPage() {
  const { deploymentName, namespaceName } = useParams<{
    deploymentName: string;
    namespaceName: string;
  }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();

  const {
    deploymentInfo,
    pods,
    replicaSets,
    events,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useDeploymentDetails(deploymentName || '', namespaceName || '');

  const [autoRefresh, setAutoRefresh] = useState(true);
  const [deploymentRefreshInterval, setDeploymentRefreshInterval] =
    useState(5000); // 5 segundos
  const [expandedSections, setExpandedSections] = useState({
    pods: true,
    replicaSets: true,
    events: true,
  });
  const [scaleModalOpen, setScaleModalOpen] = useState(false);
  const [newReplicas, setNewReplicas] = useState<number>(1);
  const [scaling, setScaling] = useState(false);
  const [restarting, setRestarting] = useState(false);
  const [yamlDrawerOpen, setYamlDrawerOpen] = useState(false);
  const [logsModalOpen, setLogsModalOpen] = useState(false);
  const [selectedPodForLogs, setSelectedPodForLogs] = useState<any>(null);

  const [deletePodModalOpen, setDeletePodModalOpen] = useState(false);
  const [podToDelete, setPodToDelete] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [deletingPod, setDeletingPod] = useState(false);
  const [restoreModalOpen, setRestoreModalOpen] = useState(false);
  const [replicaSetToRestore, setReplicaSetToRestore] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [restoring, setRestoring] = useState(false);
  const [errorModalOpen, setErrorModalOpen] = useState(false);
  const [selectedError, setSelectedError] = useState<{
    podName: string;
    error: string;
    reason: string;
    containerName?: string;
    isInitContainer?: boolean;
  } | null>(null);
  const [replicaSetModalOpen, setReplicaSetModalOpen] = useState(false);
  const [selectedReplicaSet, setSelectedReplicaSet] = useState<any>(null);
  const [replicaSetEvents, setReplicaSetEvents] = useState<any[]>([]);
  const [replicaSetPods, setReplicaSetPods] = useState<any[]>([]);
  const [loadingReplicaSetDetails, setLoadingReplicaSetDetails] =
    useState(false);
  const [eventModalOpen, setEventModalOpen] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<any>(null);
  const [deleteEventModalOpen, setDeleteEventModalOpen] = useState(false);
  const [eventToDelete, setEventToDelete] = useState<any>(null);
  const [deletingEvent, setDeletingEvent] = useState(false);
  const [deleteReplicaSetModalOpen, setDeleteReplicaSetModalOpen] =
    useState(false);
  const [replicaSetToDelete, setReplicaSetToDelete] = useState<any>(null);
  const [deleteDeploymentModalOpen, setDeleteDeploymentModalOpen] =
    useState(false);
  const [deletingDeployment, setDeletingDeployment] = useState(false);
  const [deleteServiceModalOpen, setDeleteServiceModalOpen] = useState(false);
  const [serviceToDelete, setServiceToDelete] = useState<any>(null);
  const [deletingService, setDeletingService] = useState(false);
  const [refreshingServicesAfterDelete, setRefreshingServicesAfterDelete] =
    useState(false);
  const [deletingReplicaSet, setDeletingReplicaSet] = useState(false);
  const [services, setServices] = useState<any[]>([]);
  const [loadingServices, setLoadingServices] = useState(false);
  const [servicesLoaded, setServicesLoaded] = useState(false);
  const [secrets, setSecrets] = useState<any[]>([]);
  const [loadingSecrets, setLoadingSecrets] = useState(false);
  const [configMaps, setConfigMaps] = useState<any[]>([]);
  const [loadingConfigMaps, setLoadingConfigMaps] = useState(false);
  const [configMapsLoaded, setConfigMapsLoaded] = useState(false);

  // Estado para controlar qual aba está ativa
  const [activeTab, setActiveTab] = useState(() => {
    // Recuperar aba ativa do sessionStorage (persistência apenas durante a sessão)
    const saved = sessionStorage.getItem(
      `deployment-tab-${deploymentName}-${namespaceName}`,
    );
    return saved || 'configuracoes';
  });

  // Estados para modais de YAML
  const [serviceYamlModalOpen, setServiceYamlModalOpen] = useState(false);
  const [selectedServiceName, setSelectedServiceName] = useState<string>('');
  const [secretYamlModalOpen, setSecretYamlModalOpen] = useState(false);
  const [selectedSecretName, setSelectedSecretName] = useState<string>('');
  const [configMapYamlModalOpen, setConfigMapYamlModalOpen] = useState(false);
  const [selectedConfigMapName, setSelectedConfigMapName] =
    useState<string>('');
  const [loadingYaml, setLoadingYaml] = useState(false);

  // Estados para modais de chave-valor
  const [secretKeysModalOpen, setSecretKeysModalOpen] = useState(false);
  const [selectedSecretData, setSelectedSecretData] = useState<any>(null);

  // Estados para edição do Pull Secret
  const [isEditingPullSecret, setIsEditingPullSecret] = useState(false);
  const [availableSecrets, setAvailableSecrets] = useState<any[]>([]);
  const [selectedPullSecret, setSelectedPullSecret] = useState<string>('');
  const [loadingAvailableSecrets, setLoadingAvailableSecrets] = useState(false);
  const [updatingPullSecret, setUpdatingPullSecret] = useState(false);

  // Estados para edição do Service Account
  const [isEditingServiceAccount, setIsEditingServiceAccount] = useState(false);
  const [availableServiceAccounts, setAvailableServiceAccounts] = useState<any[]>([]);
  const [selectedServiceAccount, setSelectedServiceAccount] = useState<string>('');
  const [loadingAvailableServiceAccounts, setLoadingAvailableServiceAccounts] = useState(false);
  const [updatingServiceAccount, setUpdatingServiceAccount] = useState(false);

  // Estados para edição da Image Pull Policy
  const [isEditingImagePullPolicy, setIsEditingImagePullPolicy] = useState(false);
  const [selectedImagePullPolicy, setSelectedImagePullPolicy] = useState<string>('');
  const [updatingImagePullPolicy, setUpdatingImagePullPolicy] = useState(false);

  // Estados para edição do Restart Policy
  const [isEditingRestartPolicy, setIsEditingRestartPolicy] = useState(false);
  const [selectedRestartPolicy, setSelectedRestartPolicy] = useState<string>('');
  const [updatingRestartPolicy, setUpdatingRestartPolicy] = useState(false);

  // Estados para edição de imagens de containers
  const [editingContainerImage, setEditingContainerImage] = useState<{containerIndex: number, containerType: 'regular' | 'init'} | null>(null);
  const [editingImageValue, setEditingImageValue] = useState<string>('');
  const [updatingContainerImage, setUpdatingContainerImage] = useState(false);

  // Estados para exclusão de labels e annotations
  const [deletingLabel, setDeletingLabel] = useState<string | null>(null);
  const [deletingAnnotation, setDeletingAnnotation] = useState<string | null>(null);

  const [configMapKeysModalOpen, setConfigMapKeysModalOpen] = useState(false);
  const [selectedConfigMapData, setSelectedConfigMapData] = useState<any>(null);
  const [dockerConfigModalOpen, setDockerConfigModalOpen] = useState(false);
  const [selectedDockerConfigData, setSelectedDockerConfigData] =
    useState<any>(null);

  // Função para mudar aba e persistir no sessionStorage
  const handleTabChange = (tabValue: string) => {
    setActiveTab(tabValue);
    sessionStorage.setItem(
      `deployment-tab-${deploymentName}-${namespaceName}`,
      tabValue,
    );
  };

  // Função para abrir modal YAML do Service
  const handleServiceYamlView = (serviceName: string) => {
    setSelectedServiceName(serviceName);
    setServiceYamlModalOpen(true);
  };

  // Função para abrir modal YAML do Secret
  const handleSecretYamlView = (secretName: string) => {
    setSelectedSecretName(secretName);
    setSecretYamlModalOpen(true);
  };

  // Função para abrir modal YAML do ConfigMap
  const handleConfigMapYamlView = (configMapName: string) => {
    setSelectedConfigMapName(configMapName);
    setConfigMapYamlModalOpen(true);
  };

  // Função para lidar com dockerconfigjson
  const handleDockerConfigView = async (secret: any) => {
    try {
      const command = `kubectl get secret ${secret.metadata?.name} -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result && result.success && result.data) {
        const secretData = JSON.parse(result.data);
        setSelectedDockerConfigData(secretData);
        setDockerConfigModalOpen(true);
      } else {
        showToast({
          title: 'Erro ao buscar Secret',
          description: 'Não foi possível obter os dados do Secret',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao buscar dados do Secret',
        variant: 'destructive',
      });
    }
  };

  // Funções para abrir modais de chave-valor
  const handleSecretKeysView = async (secret: any) => {
    try {
      const command = `kubectl get secret ${secret.metadata?.name} -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result && result.success && result.data) {
        const secretData = JSON.parse(result.data);
        setSelectedSecretData(secretData);
        setSecretKeysModalOpen(true);
      } else {
        showToast({
          title: 'Erro ao buscar Secret',
          description: 'Não foi possível obter os dados do Secret',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao buscar dados do Secret',
        variant: 'destructive',
      });
    }
  };

  const handleConfigMapKeysView = async (configMap: any) => {
    try {
      const command = `kubectl get configmap ${configMap.metadata?.name} -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result && result.success && result.data) {
        const configMapData = JSON.parse(result.data);
        setSelectedConfigMapData(configMapData);
        setConfigMapKeysModalOpen(true);
      } else {
        showToast({
          title: 'Erro ao buscar ConfigMap',
          description: 'Não foi possível obter os dados do ConfigMap',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao buscar dados do ConfigMap',
        variant: 'destructive',
      });
    }
  };

  // Função para buscar Services relacionados ao deployment (apenas carregamento inicial)
  const fetchRelatedServices = async () => {
    if (!deploymentName || !namespaceName) {
      return;
    }

    setLoadingServices(true);
    try {
      // Buscar todos os services no namespace
      const servicesCommand = `kubectl get services -n ${namespaceName} -o json`;
      const servicesResult = await executeCommand(servicesCommand);

      if (
        servicesResult &&
        servicesResult.success &&
        servicesResult.data &&
        typeof servicesResult.data === 'string' &&
        servicesResult.data.trim() !== 'undefined' &&
        servicesResult.data.trim() !== ''
      ) {
        let servicesData;
        try {
          servicesData = JSON.parse(servicesResult.data);
        } catch (parseError) {
          console.error('Erro ao fazer parse do JSON de services:', parseError);
          console.error('Data recebida:', servicesResult.data);
          setServices([]);
          return;
        }
        const deploymentLabels = deploymentInfo?.metadata?.labels || {};

        // Filtrar services que possuem selectors que fazem match com os labels do deployment
        const relatedServices = servicesData.items.filter((service: any) => {
          const serviceSelectors = service.spec?.selector || {};

          // Se o service não tem selectors, não pode estar relacionado ao deployment
          if (Object.keys(serviceSelectors).length === 0) {
            return false;
          }

          // Verificar se todos os selectors do service fazem match com os labels do deployment
          // (os selectors do service devem ser um subset dos labels do deployment)
          const isMatch = Object.entries(serviceSelectors).every(
            ([key, value]) => {
              return deploymentLabels[key] === value;
            },
          );

          return isMatch;
        });

        setServices(relatedServices);
      } else {
        console.error(
          'Erro ao buscar services:',
          servicesResult.error || 'Output vazio ou inválido',
        );
        setServices([]);
      }
    } catch (error) {
      console.error('Erro ao buscar services:', error);
      setServices([]);
    } finally {
      setLoadingServices(false);
    }
  };

  // Função para buscar Secrets relacionados ao deployment
  const fetchRelatedSecrets = async () => {
    if (!deploymentName || !namespaceName || !deploymentInfo) {
      return;
    }

    setLoadingSecrets(true);
    try {
      // Buscar todos os secrets no namespace
      const secretsCommand = `kubectl get secrets -n ${namespaceName} -o json`;
      const secretsResult = await executeCommand(secretsCommand);

      if (
        secretsResult &&
        secretsResult.success &&
        secretsResult.data &&
        typeof secretsResult.data === 'string' &&
        secretsResult.data.trim() !== 'undefined' &&
        secretsResult.data.trim() !== ''
      ) {
        let secretsData;
        try {
          secretsData = JSON.parse(secretsResult.data);
        } catch (parseError) {
          console.error('Erro ao fazer parse do JSON de secrets:', parseError);
          console.error('Data recebida:', secretsResult.data);
          setSecrets([]);
          return;
        }
        const containers =
          deploymentInfo.spec?.template?.spec?.containers || [];
        const initContainers =
          deploymentInfo.spec?.template?.spec?.initContainers || [];
        const allContainers = [...containers, ...initContainers];

        // Coleta informações detalhadas sobre secrets e chaves utilizadas
        const secretUsageEntries: Array<{
          secretName: string;
          usageType: string;
          keys: string[];
          isFullSecret: boolean;
        }> = [];

        allContainers.forEach((container: any) => {
          // Secrets via env (chaves específicas) - cada chave = uma entrada
          container.env?.forEach((env: any) => {
            if (
              env.valueFrom?.secretKeyRef?.name &&
              env.valueFrom?.secretKeyRef?.key
            ) {
              const secretName = env.valueFrom.secretKeyRef.name;
              const keyName = env.valueFrom.secretKeyRef.key;

              secretUsageEntries.push({
                secretName,
                usageType: 'Env',
                keys: [keyName],
                isFullSecret: false,
              });
            }
          });

          // Secrets via envFrom (secret inteiro) - uma entrada por envFrom
          container.envFrom?.forEach((envFrom: any) => {
            if (envFrom.secretRef?.name) {
              const secretName = envFrom.secretRef.name;

              secretUsageEntries.push({
                secretName,
                usageType: 'EnvFrom',
                keys: [],
                isFullSecret: true,
              });
            }
          });

          // Volume mounts com secrets - uma entrada por volume
          container.volumeMounts?.forEach((mount: any) => {
            const volume = deploymentInfo.spec?.template?.spec?.volumes?.find(
              (v: any) => v.name === mount.name,
            );
            if (volume?.secret?.secretName) {
              const { secretName } = volume.secret;

              // Se tem items específicos, coleta as chaves
              if (volume.secret.items && Array.isArray(volume.secret.items)) {
                const keys = volume.secret.items
                  .map((item: any) => item.key)
                  .filter(Boolean);
                secretUsageEntries.push({
                  secretName,
                  usageType: 'Volume',
                  keys,
                  isFullSecret: false,
                });
              } else {
                // Se não tem items específicos, usa o secret inteiro
                secretUsageEntries.push({
                  secretName,
                  usageType: 'Volume',
                  keys: [],
                  isFullSecret: true,
                });
              }
            }
          });
        });

        // Secrets de imagePullSecrets (sempre secret inteiro)
        const imagePullSecrets =
          deploymentInfo.spec?.template?.spec?.imagePullSecrets || [];
        imagePullSecrets.forEach((secret: any) => {
          if (secret.name) {
            secretUsageEntries.push({
              secretName: secret.name,
              usageType: 'ImagePull',
              keys: [],
              isFullSecret: true,
            });
          }
        });

        // Criar lista expandida - uma linha por tipo de uso
        const expandedSecrets = secretUsageEntries
          .map((entry) => {
            const secret = secretsData.items.find(
              (s: any) => s.metadata?.name === entry.secretName,
            );

            return {
              ...secret,
              usageEntry: entry,
            };
          })
          .filter((item) => item.metadata);

        setSecrets(expandedSecrets);
      } else {
        console.error(
          'Erro ao buscar secrets:',
          secretsResult.error || 'Output vazio ou inválido',
        );
        setSecrets([]);
      }
    } catch (error) {
      console.error('Erro ao buscar secrets:', error);
      setSecrets([]);
    } finally {
      setLoadingSecrets(false);
    }
  };

  // Função para buscar ConfigMaps relacionados ao deployment
  const fetchRelatedConfigMaps = async () => {
    if (!deploymentName || !namespaceName || !deploymentInfo) {
      return;
    }

    setLoadingConfigMaps(true);
    try {
      // Buscar todos os configmaps no namespace
      const configMapsCommand = `kubectl get configmaps -n ${namespaceName} -o json`;
      const configMapsResult = await executeCommand(configMapsCommand);

      if (
        configMapsResult &&
        configMapsResult.success &&
        configMapsResult.data &&
        typeof configMapsResult.data === 'string' &&
        configMapsResult.data.trim() !== 'undefined' &&
        configMapsResult.data.trim() !== ''
      ) {
        let configMapsData;
        try {
          configMapsData = JSON.parse(configMapsResult.data);
        } catch (parseError) {
          console.error(
            'Erro ao fazer parse do JSON de configmaps:',
            parseError,
          );
          console.error('Data recebida:', configMapsResult.data);
          setConfigMaps([]);
          return;
        }
        const containers =
          deploymentInfo.spec?.template?.spec?.containers || [];
        const initContainers =
          deploymentInfo.spec?.template?.spec?.initContainers || [];
        const allContainers = [...containers, ...initContainers];

        // Coleta informações detalhadas sobre configmaps e chaves utilizadas
        const configMapUsageEntries: Array<{
          configMapName: string;
          usageType: string;
          keys: string[];
          isFullConfigMap: boolean;
        }> = [];

        allContainers.forEach((container: any) => {
          // ConfigMaps via env (chaves específicas) - cada chave = uma entrada
          container.env?.forEach((env: any) => {
            if (
              env.valueFrom?.configMapKeyRef?.name &&
              env.valueFrom?.configMapKeyRef?.key
            ) {
              const configMapName = env.valueFrom.configMapKeyRef.name;
              const keyName = env.valueFrom.configMapKeyRef.key;

              configMapUsageEntries.push({
                configMapName,
                usageType: 'Env',
                keys: [keyName],
                isFullConfigMap: false,
              });
            }
          });

          // ConfigMaps via envFrom (configmap inteiro) - uma entrada por envFrom
          container.envFrom?.forEach((envFrom: any) => {
            if (envFrom.configMapRef?.name) {
              const configMapName = envFrom.configMapRef.name;

              configMapUsageEntries.push({
                configMapName,
                usageType: 'EnvFrom',
                keys: [],
                isFullConfigMap: true,
              });
            }
          });

          // Volume mounts com configmaps - uma entrada por volume
          container.volumeMounts?.forEach((mount: any) => {
            const volume = deploymentInfo.spec?.template?.spec?.volumes?.find(
              (v: any) => v.name === mount.name,
            );
            if (volume?.configMap?.name) {
              const configMapName = volume.configMap.name;

              // Se tem items específicos, coleta as chaves
              if (
                volume.configMap.items &&
                Array.isArray(volume.configMap.items)
              ) {
                const keys = volume.configMap.items
                  .map((item: any) => item.key)
                  .filter(Boolean);
                configMapUsageEntries.push({
                  configMapName,
                  usageType: 'Volume',
                  keys,
                  isFullConfigMap: false,
                });
              } else {
                // Se não tem items específicos, usa o configmap inteiro
                configMapUsageEntries.push({
                  configMapName,
                  usageType: 'Volume',
                  keys: [],
                  isFullConfigMap: true,
                });
              }
            }
          });
        });

        // Criar lista expandida - uma linha por tipo de uso
        const expandedConfigMaps = configMapUsageEntries
          .map((entry) => {
            const configMap = configMapsData.items.find(
              (cm: any) => cm.metadata?.name === entry.configMapName,
            );

            return {
              ...configMap,
              usageEntry: entry,
            };
          })
          .filter((item) => item.metadata);

        setConfigMaps(expandedConfigMaps);
      } else {
        setConfigMaps([]);
      }
    } catch (error) {
      console.error('Erro ao buscar configmaps relacionados:', error);
      setConfigMaps([]);
    } finally {
      setLoadingConfigMaps(false);
    }
  };

  // Buscar Services APENAS uma vez quando o deployment for carregado inicialmente
  useEffect(() => {
    if (deploymentInfo && !loading && !servicesLoaded) {
      // Adicionar um pequeno delay para evitar problemas de concorrência
      setTimeout(() => {
        fetchRelatedServices(); // Carrega services apenas uma vez
        setServicesLoaded(true); // Marca como carregado para não executar novamente
      }, 100);
    }
  }, [deploymentInfo, loading, servicesLoaded]);

  // Buscar Secrets APENAS uma vez quando o deployment for carregado inicialmente
  const [secretsLoaded, setSecretsLoaded] = useState(false);
  useEffect(() => {
    if (deploymentInfo && !loading && !secretsLoaded) {
      // Adicionar um pequeno delay para evitar problemas de concorrência
      setTimeout(() => {
        fetchRelatedSecrets();
        setSecretsLoaded(true);
      }, 100);
    }
  }, [deploymentInfo, loading, secretsLoaded]);

  // Buscar ConfigMaps APENAS uma vez quando o deployment for carregado inicialmente
  useEffect(() => {
    if (deploymentInfo && !loading && !configMapsLoaded) {
      // Adicionar um pequeno delay para evitar problemas de concorrência
      setTimeout(() => {
        fetchRelatedConfigMaps();
        setConfigMapsLoaded(true);
      }, 100);
    }
  }, [deploymentInfo, loading, configMapsLoaded]);

  // Limpar sessionStorage quando o componente desmontar
  useEffect(() => {
    return () => {
      // Cleanup ao sair da página - limpar a persistência da aba
      const currentKey = `deployment-tab-${deploymentName}-${namespaceName}`;
      sessionStorage.removeItem(currentKey);
    };
  }, [deploymentName, namespaceName]);

  // Função para obter o status do Service
  const getServiceStatus = (service: any) => {
    const serviceType = service.spec?.type || 'ClusterIP';
    const externalIP =
      service.status?.loadBalancer?.ingress?.[0]?.ip ||
      service.status?.loadBalancer?.ingress?.[0]?.hostname;

    if (serviceType === 'LoadBalancer') {
      if (externalIP) {
        return { status: 'Active', color: 'text-green-600', icon: CheckCircle };
      }
      return { status: 'Pending', color: 'text-yellow-600', icon: Clock };
    }
    if (serviceType === 'NodePort') {
      return { status: 'Active', color: 'text-green-600', icon: CheckCircle };
    }
    return { status: 'Active', color: 'text-blue-600', icon: CheckCircle };
  };

  // Função para obter informações do Secret
  const getSecretInfo = (secret: any) => {
    const secretType = secret.type || 'Opaque';
    const dataKeys = Object.keys(secret.data || {});

    let variant = 'secondary';
    let icon = Shield;

    if (secretType === 'kubernetes.io/dockerconfigjson') {
      variant = 'outline';
      icon = Container;
    } else if (secretType === 'kubernetes.io/tls') {
      variant = 'destructive';
      icon = Shield;
    }

    return {
      type: secretType,
      variant,
      icon,
      keysCount: dataKeys.length,
      keys: dataKeys,
    };
  };

  // Função para determinar como exibir as chaves baseado no tipo do Secret
  const getSecretKeysDisplay = (secret: any, usageEntry: any) => {
    const secretType = secret.type || 'Opaque';
    const secretInfo = getSecretInfo(secret);

    // Para tipos específicos, use descrições padronizadas
    switch (secretType) {
      case 'kubernetes.io/dockerconfigjson':
        return {
          type: 'special',
          badge: 'Registry Config',
          tooltip: 'Credenciais de registry Docker',
          color: 'bg-purple-50 text-purple-700',
        };

      case 'kubernetes.io/tls':
        return {
          type: 'special',
          badge: 'Certificado SSL',
          tooltip: 'Certificado TLS (tls.crt, tls.key)',
          color: 'bg-red-50 text-red-700',
        };

      case 'kubernetes.io/service-account-token':
        return {
          type: 'special',
          badge: 'Token de Serviço',
          tooltip: 'Token de autenticação do Service Account',
          color: 'bg-yellow-50 text-yellow-700',
        };

      default:
        // Para Opaque e outros tipos, use a lógica normal de chaves
        if (usageEntry.isFullSecret) {
          return {
            type: 'all-keys',
            keys: secretInfo.keys,
            color: 'bg-green-50 text-green-700',
            clickable: true,
          };
        }
        if (usageEntry.keys.length > 0) {
          return {
            type: 'specific-keys',
            keys: usageEntry.keys,
            color: 'bg-blue-50 text-blue-700',
            clickable: true,
          };
        }
        return {
          type: 'unspecified',
          color: '',
          clickable: false,
        };
    }
  };

  // Função para obter informações do ConfigMap
  const getConfigMapInfo = (configMap: any) => {
    const dataKeys = Object.keys(configMap.data || {});

    return {
      keysCount: dataKeys.length,
      keys: dataKeys,
      size: JSON.stringify(configMap.data || {}).length,
    };
  };

  // Auto-refresh with configurable interval
  useEffect(() => {
    if (!autoRefresh) return;

    const intervalId = setInterval(async () => {
      if (
        !scaleModalOpen &&
        !scaling &&
        !restarting &&
        !yamlDrawerOpen &&
        !isRefreshing &&
        !deletePodModalOpen &&
        !deletingPod &&
        !restoreModalOpen &&
        !restoring &&
        !replicaSetModalOpen &&
        !eventModalOpen &&
        !deleteEventModalOpen &&
        !deletingEvent &&
        !deleteReplicaSetModalOpen &&
        !deletingReplicaSet &&
        !deleteDeploymentModalOpen &&
        !deletingDeployment &&
        !deleteServiceModalOpen &&
        !deletingService &&
        !refreshingServicesAfterDelete
      ) {
        await backgroundRefetch();
      }
    }, deploymentRefreshInterval);

    return () => {
      clearInterval(intervalId);
    };
  }, [
    autoRefresh,
    deploymentRefreshInterval,
    scaleModalOpen,
    scaling,
    restarting,
    yamlDrawerOpen,
    isRefreshing,
    deletePodModalOpen,
    deletingPod,
    restoreModalOpen,
    restoring,
    replicaSetModalOpen,
    eventModalOpen,
    deleteEventModalOpen,
    deletingEvent,
    deleteReplicaSetModalOpen,
    deletingReplicaSet,
    deleteDeploymentModalOpen,
    deletingDeployment,
    deleteServiceModalOpen,
    deletingService,
    refreshingServicesAfterDelete,
    backgroundRefetch,
  ]);

  const toggleSection = (section: keyof typeof expandedSections) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  const handleScale = () => {
    if (deploymentInfo) {
      setNewReplicas(deploymentInfo.spec?.replicas || 1);
      setScaleModalOpen(true);
    }
  };

  const handleRestart = async () => {
    if (!deploymentName || !namespaceName) return;

    setRestarting(true);
    try {
      const command = `kubectl rollout restart deployment/${deploymentName} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Restart Iniciado',
          description: `O deployment "${deploymentName}" está sendo reiniciado`,
          variant: 'success',
        });
        // Fazer refresh automático após 2 segundos para mostrar o progresso
        setTimeout(() => {
          backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Reiniciar',
          description: result.error || 'Falha ao reiniciar o deployment',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setRestarting(false);
    }
  };

  const handleYamlView = () => {
    if (!deploymentName || !namespaceName) return;
    setYamlDrawerOpen(true);
  };

  const handlePodLogs = (pod: any, containerName?: string) => {
    if (!pod?.metadata?.name || !namespaceName) return;

    setSelectedPodForLogs(pod);
    setLogsModalOpen(true);
  };

  const handleDownloadLogs = () => {
    if (!podLogs || !selectedPodForLogs?.metadata?.name || !namespaceName)
      return;

    try {
      // Usar logs filtrados se houver filtros ativos
      const logsToDownload = getFilteredLogs();

      // Criar um blob com o conteúdo dos logs
      const blob = new Blob([logsToDownload], { type: 'text/plain' });

      // Criar URL temporária para o blob
      const url = URL.createObjectURL(blob);

      // Criar elemento de link temporário
      const link = document.createElement('a');
      link.href = url;

      // Nome do arquivo com indicação de filtro se aplicável
      const filterSuffix =
        logsFilter || logsLevelFilter !== 'all' || logsDateFrom || logsDateTo
          ? '-filtered'
          : '';
      link.download = `${selectedPodForLogs.metadata.name}-${namespaceName}${filterSuffix}.log`;

      // Adicionar ao DOM, clicar e remover
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // Limpar URL temporária
      URL.revokeObjectURL(url);
    } catch (err) {
      showToast({
        title: 'Erro no Download',
        description: 'Não foi possível baixar o arquivo de logs',
        variant: 'destructive',
      });
    }
  };

  // Função para refresh manual dos logs
  const handleManualRefresh = async () => {
    if (!selectedPodForLogs?.metadata?.name || !namespaceName) return;

    setLoadingLogs(true);
    try {
      const command = `kubectl logs ${selectedPodForLogs.metadata.name} -n ${namespaceName} --tail=1000`;
      const result = await executeCommand(command);

      if (result.success) {
        const logs = result.data || 'Nenhum log disponível';
        // Limitar a 2000 linhas para manter performance
        const lines = logs.split('\n');
        if (lines.length > 2000) {
          setPodLogs(lines.slice(-2000).join('\n'));
        } else {
          setPodLogs(logs);
        }
        setLastLogTimestamp(new Date().toISOString()); // Atualizar timestamp
        showToast({
          title: 'Logs Atualizados',
          description: 'Logs carregados com sucesso',
          variant: 'success',
        });
      } else {
        showToast({
          title: 'Erro ao Atualizar',
          description: result.error || 'Erro ao carregar logs',
          variant: 'destructive',
        });
      }
    } catch (err) {
      showToast({
        title: 'Erro ao Atualizar',
        description: 'Não foi possível atualizar os logs',
        variant: 'destructive',
      });
    } finally {
      setLoadingLogs(false);
    }
  };

  // Função para limpar logs
  const handleClearLogs = () => {
    setPodLogs('');
    setLastLogTimestamp(new Date().toISOString()); // Reset timestamp para começar fresh
    showToast({
      title: 'Logs Limpos',
      description: 'Tela de logs foi limpa. Novos logs aparecerão aqui.',
      variant: 'success',
    });
  };

  // Função para iniciar edição do YAML

  const handleConfirmScale = async () => {
    if (!deploymentName || !namespaceName) return;

    setScaling(true);
    try {
      const command = `kubectl scale deployment ${deploymentName} --replicas=${newReplicas} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Deployment Escalado',
          description: `O deployment "${deploymentName}" foi escalado para ${newReplicas} réplica(s)`,
          variant: 'success',
        });
        setScaleModalOpen(false);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Escalar Deployment',
          description: result.error || 'Falha ao escalar deployment',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setScaling(false);
    }
  };

  const incrementReplicas = () => {
    setNewReplicas((prev) => Math.min(prev + 1, 100));
  };

  const decrementReplicas = () => {
    setNewReplicas((prev) => Math.max(prev - 1, 0));
  };

  const handleDeletePodClick = (podName: string, podNamespace: string) => {
    setPodToDelete({ name: podName, namespace: podNamespace });
    setDeletePodModalOpen(true);
  };

  const handleConfirmDeletePod = async () => {
    if (!podToDelete) return;

    setDeletingPod(true);
    try {
      const command = `kubectl delete pod ${podToDelete.name} -n ${podToDelete.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Pod Deletado',
          description: `O pod "${podToDelete.name}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeletePodModalOpen(false);
        setPodToDelete(null);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Deletar Pod',
          description: result.error || 'Falha ao deletar pod',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingPod(false);
    }
  };

  const handleRestoreClick = (
    replicaSetName: string,
    replicaSetNamespace: string,
  ) => {
    setReplicaSetToRestore({
      name: replicaSetName,
      namespace: replicaSetNamespace,
    });
    setRestoreModalOpen(true);
  };

  const handleConfirmRestore = async () => {
    if (!replicaSetToRestore || !deploymentName) return;

    setRestoring(true);
    try {
      // Usa kubectl rollout undo para reverter para um ReplicaSet específico
      // Primeiro precisamos encontrar a revision do ReplicaSet
      const historyCommand = `kubectl rollout history deployment/${deploymentName} -n ${namespaceName}`;
      const historyResult = await executeCommand(historyCommand);

      if (!historyResult.success) {
        throw new Error('Falha ao obter histórico do deployment');
      }

      // Para simplicidade, vamos usar rollout undo para a revision anterior
      // Em um ambiente real, você precisaria mapear o ReplicaSet para a revision específica
      const rollbackCommand = `kubectl rollout undo deployment/${deploymentName} -n ${namespaceName}`;
      const result = await executeCommand(rollbackCommand);

      if (result.success) {
        showToast({
          title: 'Deployment Restaurado',
          description: `O deployment "${deploymentName}" foi restaurado com sucesso`,
          variant: 'success',
        });
        setRestoreModalOpen(false);
        setReplicaSetToRestore(null);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Restaurar Deployment',
          description: result.error || 'Falha ao restaurar deployment',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setRestoring(false);
    }
  };

  const handleErrorClick = (
    podName: string,
    reason: string,
    message: string,
    containerName?: string,
    isInitContainer?: boolean,
  ) => {
    setSelectedError({
      podName,
      reason,
      error: message,
      containerName,
      isInitContainer,
    });
    setErrorModalOpen(true);
  };

  const handleReplicaSetClick = async (replicaSet: any) => {
    setSelectedReplicaSet(replicaSet);
    setReplicaSetModalOpen(true);
    setLoadingReplicaSetDetails(true);

    try {
      // Buscar eventos específicos do ReplicaSet
      const eventsRes = await executeCommand(
        `kubectl get events -n ${namespaceName} --field-selector involvedObject.kind=ReplicaSet,involvedObject.name=${replicaSet.metadata?.name} --sort-by='.lastTimestamp' -o json`,
      );

      // Buscar pods específicos deste ReplicaSet
      const replicaSetUid = replicaSet.metadata?.uid;
      const relatedPods = pods.filter((pod: any) => {
        const ownerRefs = pod.metadata?.ownerReferences || [];
        return ownerRefs.some(
          (ref: any) => ref.uid === replicaSetUid && ref.kind === 'ReplicaSet',
        );
      });

      // Processar eventos
      let parsedEvents = [];
      if (eventsRes.success) {
        const eventsData =
          typeof eventsRes.data === 'string'
            ? JSON.parse(eventsRes.data)
            : eventsRes.data;
        parsedEvents = eventsData.items || [];
      }

      setReplicaSetEvents(parsedEvents);
      setReplicaSetPods(relatedPods);
    } catch (err) {
      console.error('Error fetching ReplicaSet details:', err);
      setReplicaSetEvents([]);
      setReplicaSetPods([]);
    } finally {
      setLoadingReplicaSetDetails(false);
    }
  };

  const handleEventClick = (event: any) => {
    setSelectedEvent(event);
    setEventModalOpen(true);
  };

  const handleDeleteEventClick = (event: any) => {
    setEventToDelete(event);
    setDeleteEventModalOpen(true);
  };

  const handleConfirmDeleteEvent = async () => {
    if (!eventToDelete) return;

    setDeletingEvent(true);
    try {
      const command = `kubectl delete event ${eventToDelete.metadata?.name} -n ${eventToDelete.metadata?.namespace || namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Evento Deletado',
          description: `O evento "${eventToDelete.reason}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteEventModalOpen(false);
        setEventToDelete(null);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Deletar Evento',
          description: result.error || 'Falha ao deletar evento',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingEvent(false);
    }
  };

  const handleDeleteReplicaSetClick = (replicaSet: any) => {
    setReplicaSetToDelete(replicaSet);
    setDeleteReplicaSetModalOpen(true);
  };

  const handleConfirmDeleteReplicaSet = async () => {
    if (!replicaSetToDelete) return;

    setDeletingReplicaSet(true);
    try {
      const command = `kubectl delete replicaset ${replicaSetToDelete.metadata?.name} -n ${replicaSetToDelete.metadata?.namespace || namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'ReplicaSet Deletado',
          description: `O ReplicaSet "${replicaSetToDelete.metadata?.name}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteReplicaSetModalOpen(false);
        setReplicaSetToDelete(null);
        // Aguardar 2 segundos antes de atualizar para permitir que o kubectl processe
        setTimeout(async () => {
          await backgroundRefetch();
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Deletar ReplicaSet',
          description: result.error || 'Falha ao deletar ReplicaSet',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingReplicaSet(false);
    }
  };

  // Função para deletar o deployment
  const handleDeleteDeploymentClick = () => {
    setDeleteDeploymentModalOpen(true);
  };

  const handleConfirmDeleteDeployment = async () => {
    if (!deploymentName || !namespaceName) return;

    setDeletingDeployment(true);
    try {
      const command = `kubectl delete deployment ${deploymentName} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Deployment Deletado',
          description: `O deployment "${deploymentName}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteDeploymentModalOpen(false);

        // Redirecionar para a lista de deployments após deletar
        setTimeout(() => {
          navigate('/workloads/deployments');
        }, 2000);
      } else {
        showToast({
          title: 'Erro ao Deletar Deployment',
          description: result.error || 'Falha ao deletar deployment',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingDeployment(false);
    }
  };

  // Função para deletar o service
  const handleDeleteServiceClick = (service: any) => {
    setServiceToDelete(service);
    setDeleteServiceModalOpen(true);
  };

  // Função para buscar secrets disponíveis para Pull Secret
  const fetchAvailableSecrets = async () => {
    if (!namespaceName) return;

    setLoadingAvailableSecrets(true);
    try {
      const command = `kubectl get secrets -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result.success && result.data) {
        const secretsData = JSON.parse(result.data);
        // Filtrar apenas secrets do tipo docker-registry
        const dockerSecrets = secretsData.items.filter(
          (secret: any) => secret.type === 'kubernetes.io/dockerconfigjson'
        );
        setAvailableSecrets(dockerSecrets);
      }
    } catch (error) {
      console.error('Erro ao buscar secrets disponíveis:', error);
      setAvailableSecrets([]);
    } finally {
      setLoadingAvailableSecrets(false);
    }
  };

  // Função para iniciar edição do Pull Secret
  const handleEditPullSecret = () => {
    const currentPullSecret = deploymentInfo?.spec?.template?.spec?.imagePullSecrets?.[0]?.name || 'none';
    setSelectedPullSecret(currentPullSecret);
    setIsEditingPullSecret(true);
    fetchAvailableSecrets();
  };

  // Função para cancelar edição do Pull Secret
  const handleCancelEditPullSecret = () => {
    setIsEditingPullSecret(false);
    setSelectedPullSecret('none');
  };

  // Função para salvar Pull Secret
  const handleSavePullSecret = async () => {
    if (!deploymentName || !namespaceName) return;

    setUpdatingPullSecret(true);
    try {
      // Criar o patch para atualizar o imagePullSecrets
      const patchData = {
        spec: {
          template: {
            spec: {
              imagePullSecrets: selectedPullSecret !== 'none' ? [{ name: selectedPullSecret }] : []
            }
          }
        }
      };

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='merge' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Pull Secret Atualizado',
          description: `Pull Secret ${selectedPullSecret !== 'none' ? `"${selectedPullSecret}"` : 'removido'} com sucesso`,
          variant: 'success',
        });
        setIsEditingPullSecret(false);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Atualizar Pull Secret',
          description: result.error || 'Falha ao atualizar Pull Secret',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao atualizar Pull Secret',
        variant: 'destructive',
      });
    } finally {
      setUpdatingPullSecret(false);
    }
  };

  // Função para iniciar edição da Image Pull Policy
  const handleEditImagePullPolicy = () => {
    // Obter a imagePullPolicy do primeiro container
    const currentImagePullPolicy = deploymentInfo?.spec?.template?.spec?.containers?.[0]?.imagePullPolicy || 'IfNotPresent';
    setSelectedImagePullPolicy(currentImagePullPolicy);
    setIsEditingImagePullPolicy(true);
  };

  // Função para cancelar edição da Image Pull Policy
  const handleCancelEditImagePullPolicy = () => {
    setIsEditingImagePullPolicy(false);
    setSelectedImagePullPolicy('');
  };

  // Função para salvar Image Pull Policy
  const handleSaveImagePullPolicy = async () => {
    if (!deploymentName || !namespaceName) return;

    setUpdatingImagePullPolicy(true);
    try {
      // Criar o patch para atualizar a imagePullPolicy em todos os containers
      const containers = deploymentInfo?.spec?.template?.spec?.containers || [];
      const updatedContainers = containers.map((container: any) => ({
        ...container,
        imagePullPolicy: selectedImagePullPolicy
      }));

      const patchData = {
        spec: {
          template: {
            spec: {
              containers: updatedContainers
            }
          }
        }
      };

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='merge' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Image Pull Policy Atualizada',
          description: `Image Pull Policy alterada para "${selectedImagePullPolicy}" com sucesso`,
          variant: 'success',
        });
        setIsEditingImagePullPolicy(false);
        await refetch();
      } else {
        const errorMessage = result.error || 'Falha ao atualizar Image Pull Policy';
        
        // Verificar se é erro de autenticação
        if (errorMessage.includes('You must be logged in') || errorMessage.includes('provide credentials')) {
          showToast({
            title: 'Erro de Autenticação',
            description: 'Você precisa estar logado no cluster. Verifique suas credenciais do kubeconfig.',
            variant: 'destructive',
          });
        } else {
          showToast({
            title: 'Erro ao Atualizar Image Pull Policy',
            description: errorMessage,
            variant: 'destructive',
          });
        }
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao atualizar Image Pull Policy',
        variant: 'destructive',
      });
    } finally {
      setUpdatingImagePullPolicy(false);
    }
  };

  // Função para iniciar edição do Restart Policy
  const handleEditRestartPolicy = () => {
    const currentRestartPolicy = deploymentInfo?.spec?.template?.spec?.restartPolicy || 'Always';
    setSelectedRestartPolicy(currentRestartPolicy);
    setIsEditingRestartPolicy(true);
  };

  // Função para cancelar edição do Restart Policy
  const handleCancelEditRestartPolicy = () => {
    setIsEditingRestartPolicy(false);
    setSelectedRestartPolicy('');
  };

  // Função para salvar Restart Policy
  const handleSaveRestartPolicy = async () => {
    if (!deploymentName || !namespaceName) return;

    setUpdatingRestartPolicy(true);
    try {
      const patchData = {
        spec: {
          template: {
            spec: {
              restartPolicy: selectedRestartPolicy
            }
          }
        }
      };

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='merge' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Restart Policy Atualizada',
          description: `Restart Policy alterada para "${selectedRestartPolicy}" com sucesso`,
          variant: 'success',
        });
        setIsEditingRestartPolicy(false);
        await refetch();
      } else {
        const errorMessage = result.error || 'Falha ao atualizar Restart Policy';
        
        // Verificar se é erro de autenticação
        if (errorMessage.includes('You must be logged in') || errorMessage.includes('provide credentials')) {
          showToast({
            title: 'Erro de Autenticação',
            description: 'Você precisa estar logado no cluster. Verifique suas credenciais do kubeconfig.',
            variant: 'destructive',
          });
        } else {
          showToast({
            title: 'Erro ao Atualizar Restart Policy',
            description: errorMessage,
            variant: 'destructive',
          });
        }
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao atualizar Restart Policy',
        variant: 'destructive',
      });
    } finally {
      setUpdatingRestartPolicy(false);
    }
  };

  // Função para iniciar edição de imagem de container
  const handleEditContainerImage = (containerIndex: number, containerType: 'regular' | 'init', currentImage: string) => {
    setEditingContainerImage({ containerIndex, containerType });
    setEditingImageValue(currentImage);
  };

  // Função para cancelar edição de imagem de container
  const handleCancelEditContainerImage = () => {
    setEditingContainerImage(null);
    setEditingImageValue('');
  };

  // Função para salvar imagem de container
  const handleSaveContainerImage = async () => {
    if (!deploymentName || !namespaceName || !editingContainerImage) return;

    setUpdatingContainerImage(true);
    try {
      const containers = deploymentInfo?.spec?.template?.spec?.containers || [];
      const initContainers = deploymentInfo?.spec?.template?.spec?.initContainers || [];

      let updatedContainers = [...containers];
      let updatedInitContainers = [...initContainers];

      if (editingContainerImage.containerType === 'regular') {
        updatedContainers[editingContainerImage.containerIndex] = {
          ...updatedContainers[editingContainerImage.containerIndex],
          image: editingImageValue
        };
      } else {
        updatedInitContainers[editingContainerImage.containerIndex] = {
          ...updatedInitContainers[editingContainerImage.containerIndex],
          image: editingImageValue
        };
      }

      const patchData: any = {
        spec: {
          template: {
            spec: {
              containers: updatedContainers
            }
          }
        }
      };

      // Adicionar initContainers apenas se existirem
      if (initContainers.length > 0) {
        patchData.spec.template.spec.initContainers = updatedInitContainers;
      }

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='merge' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Imagem Atualizada',
          description: `Imagem do container alterada para "${editingImageValue}" com sucesso`,
          variant: 'success',
        });
        setEditingContainerImage(null);
        setEditingImageValue('');
        await refetch();
      } else {
        const errorMessage = result.error || 'Falha ao atualizar imagem do container';
        
        // Verificar se é erro de autenticação
        if (errorMessage.includes('You must be logged in') || errorMessage.includes('provide credentials')) {
          showToast({
            title: 'Erro de Autenticação',
            description: 'Você precisa estar logado no cluster. Verifique suas credenciais do kubeconfig.',
            variant: 'destructive',
          });
        } else {
          showToast({
            title: 'Erro ao Atualizar Imagem',
            description: errorMessage,
            variant: 'destructive',
          });
        }
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao atualizar imagem do container',
        variant: 'destructive',
      });
    } finally {
      setUpdatingContainerImage(false);
    }
  };

  // Função para excluir label
  const handleDeleteLabel = async (labelKey: string) => {
    if (!deploymentName || !namespaceName) return;

    setDeletingLabel(labelKey);
    try {
      // Usar JSON patch para remover o label específico
      // Escape correto: ~ -> ~0, / -> ~1
      const escapedKey = labelKey.replace(/~/g, '~0').replace(/\//g, '~1');
      const patchData = [
        {
          op: "remove",
          path: `/metadata/labels/${escapedKey}`
        }
      ];

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='json' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Label Removido',
          description: `Label "${labelKey}" foi removido com sucesso`,
          variant: 'success',
        });
        await refetch();
      } else {
        const errorMessage = result.error || 'Falha ao remover label';
        
        if (errorMessage.includes('You must be logged in') || errorMessage.includes('provide credentials')) {
          showToast({
            title: 'Erro de Autenticação',
            description: 'Você precisa estar logado no cluster. Verifique suas credenciais do kubeconfig.',
            variant: 'destructive',
          });
        } else {
          showToast({
            title: 'Erro ao Remover Label',
            description: errorMessage,
            variant: 'destructive',
          });
        }
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao remover label',
        variant: 'destructive',
      });
    } finally {
      setDeletingLabel(null);
    }
  };

  // Função para excluir annotation
  const handleDeleteAnnotation = async (annotationKey: string) => {
    if (!deploymentName || !namespaceName) return;

    setDeletingAnnotation(annotationKey);
    try {
      // Usar JSON patch para remover a annotation específica
      // Escape correto: ~ -> ~0, / -> ~1
      const escapedKey = annotationKey.replace(/~/g, '~0').replace(/\//g, '~1');
      const patchData = [
        {
          op: "remove",
          path: `/metadata/annotations/${escapedKey}`
        }
      ];

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='json' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Annotation Removida',
          description: `Annotation "${annotationKey}" foi removida com sucesso`,
          variant: 'success',
        });
        await refetch();
      } else {
        const errorMessage = result.error || 'Falha ao remover annotation';
        
        if (errorMessage.includes('You must be logged in') || errorMessage.includes('provide credentials')) {
          showToast({
            title: 'Erro de Autenticação',
            description: 'Você precisa estar logado no cluster. Verifique suas credenciais do kubeconfig.',
            variant: 'destructive',
          });
        } else {
          showToast({
            title: 'Erro ao Remover Annotation',
            description: errorMessage,
            variant: 'destructive',
          });
        }
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao remover annotation',
        variant: 'destructive',
      });
    } finally {
      setDeletingAnnotation(null);
    }
  };

  // Função para buscar service accounts disponíveis
  const fetchAvailableServiceAccounts = async () => {
    if (!namespaceName) return;

    setLoadingAvailableServiceAccounts(true);
    try {
      const command = `kubectl get serviceaccounts -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result.success && result.data) {
        const serviceAccountsData = JSON.parse(result.data);
        setAvailableServiceAccounts(serviceAccountsData.items);
      }
    } catch (error) {
      console.error('Erro ao buscar service accounts disponíveis:', error);
      setAvailableServiceAccounts([]);
    } finally {
      setLoadingAvailableServiceAccounts(false);
    }
  };

  // Função para iniciar edição do Service Account
  const handleEditServiceAccount = () => {
    const currentServiceAccount = deploymentInfo?.spec?.template?.spec?.serviceAccountName || 'default';
    setSelectedServiceAccount(currentServiceAccount);
    setIsEditingServiceAccount(true);
    fetchAvailableServiceAccounts();
  };

  // Função para cancelar edição do Service Account
  const handleCancelEditServiceAccount = () => {
    setIsEditingServiceAccount(false);
    setSelectedServiceAccount('default');
  };

  // Função para salvar Service Account
  const handleSaveServiceAccount = async () => {
    if (!deploymentName || !namespaceName) return;

    setUpdatingServiceAccount(true);
    try {
      // Criar o patch para atualizar o serviceAccountName
      const patchData = {
        spec: {
          template: {
            spec: {
              serviceAccountName: selectedServiceAccount
            }
          }
        }
      };

      const command = `kubectl patch deployment ${deploymentName} -n ${namespaceName} --type='merge' -p '${JSON.stringify(patchData)}'`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Service Account Atualizado',
          description: `Service Account alterado para "${selectedServiceAccount}" com sucesso`,
          variant: 'success',
        });
        setIsEditingServiceAccount(false);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Atualizar Service Account',
          description: result.error || 'Falha ao atualizar Service Account',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: 'Erro inesperado ao atualizar Service Account',
        variant: 'destructive',
      });
    } finally {
      setUpdatingServiceAccount(false);
    }
  };

  const handleConfirmDeleteService = async () => {
    if (!serviceToDelete) return;

    setDeletingService(true);
    try {
      const command = `kubectl delete service ${serviceToDelete.metadata?.name} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Service Deletado',
          description: `O service "${serviceToDelete.metadata?.name}" foi deletado com sucesso. Atualizando lista...`,
          variant: 'success',
        });
        setDeleteServiceModalOpen(false);
        setServiceToDelete(null);

        // Iniciar loading da atualização
        setRefreshingServicesAfterDelete(true);

        // Aguardar 3 segundos e então atualizar a lista de services
        setTimeout(async () => {
          try {
            await fetchRelatedServices();
          } catch (error) {
            console.error('Erro ao atualizar lista de services:', error);
          } finally {
            setRefreshingServicesAfterDelete(false);
          }
        }, 3000);
      } else {
        showToast({
          title: 'Erro ao Deletar Service',
          description: result.error || 'Falha ao deletar service',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeletingService(false);
    }
  };

  const getDeploymentStatus = () => {
    if (!deploymentInfo)
      return { status: 'Unknown', variant: 'secondary' as const };

    const readyReplicas = deploymentInfo.status?.readyReplicas || 0;
    const replicas = deploymentInfo.spec?.replicas || 0;
    const updatedReplicas = deploymentInfo.status?.updatedReplicas || 0;
    const availableReplicas = deploymentInfo.status?.availableReplicas || 0;

    // Verifica o estado real dos pods
    const totalPods = pods.length;
    const podsWithErrors = pods.filter((pod) => {
      const containerStatuses = pod.status?.containerStatuses || [];
      return containerStatuses.some(
        (container) =>
          container.state?.waiting?.reason === 'ImagePullBackOff' ||
          container.state?.waiting?.reason === 'ErrImagePull' ||
          container.state?.waiting?.reason === 'CrashLoopBackOff' ||
          container.state?.waiting?.reason === 'CreateContainerConfigError',
      );
    }).length;

    const podsRunningButNotReady = pods.filter((pod) => {
      const phase = pod.status?.phase;
      const readyContainers =
        pod.status?.containerStatuses?.filter((c: any) => c.ready).length || 0;
      const totalContainers = pod.status?.containerStatuses?.length || 0;
      return phase === 'Running' && readyContainers < totalContainers;
    }).length;

    // Verifica se está em processo de rollout/update
    const conditions = deploymentInfo.status?.conditions || [];
    const progressing = conditions.find((c: any) => c.type === 'Progressing');
    const isProgressing =
      progressing?.status === 'True' &&
      progressing?.reason === 'ReplicaSetUpdated';

    // Se tem pods com problemas ou está fazendo rollout/update
    if (
      isProgressing ||
      updatedReplicas < replicas ||
      podsWithErrors > 0 ||
      podsRunningButNotReady > 0
    ) {
      return {
        status: 'Updating',
        variant: 'secondary' as const,
        color: 'bg-orange-500 hover:bg-orange-600 text-white',
      };
    }

    // Se tem mais pods do que deveria (durante rollout)
    if (totalPods > replicas) {
      return {
        status: 'Updating',
        variant: 'secondary' as const,
        color: 'bg-orange-500 hover:bg-orange-600 text-white',
      };
    }

    // Se todas as réplicas estão prontas E sem problemas
    if (
      readyReplicas === replicas &&
      replicas > 0 &&
      availableReplicas === replicas &&
      podsWithErrors === 0
    ) {
      return {
        status: 'Ready',
        variant: 'default' as const,
        color: 'bg-green-500 hover:bg-green-600',
      };
    }

    // Se tem réplicas prontas mas não todas
    if (readyReplicas > 0 && readyReplicas < replicas) {
      return {
        status: 'Partial',
        variant: 'secondary' as const,
        color: 'bg-yellow-500 hover:bg-yellow-600',
      };
    }

    // Se está escalado para 0
    if (replicas === 0) {
      return { status: 'Scaled Down', variant: 'outline' as const };
    }

    // Se não tem réplicas prontas
    return { status: 'Not Ready', variant: 'destructive' as const };
  };

  const getPodStatus = (pod: any) => {
    const phase = pod.status?.phase;
    if (phase === 'Running')
      return { icon: CheckCircle, color: 'text-green-600' };
    if (phase === 'Pending') return { icon: Clock, color: 'text-yellow-600' };
    if (phase === 'Failed') return { icon: XCircle, color: 'text-red-600' };
    return { icon: AlertTriangle, color: 'text-gray-600' };
  };

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

    if (diffDays > 0) return `${diffDays} dias`;
    if (diffHours > 0) return `${diffHours}h`;
    return `${diffMinutes}m`;
  };

  const getPodReason = (pod: any) => {
    // Debug: Log da estrutura do pod para casos com erro
    if (
      pod.status?.phase !== 'Running' ||
      (pod.status?.containerStatuses || []).some((c: any) => !c.ready) ||
      (pod.status?.initContainerStatuses || []).some((c: any) => !c.ready)
    ) {
      console.log('Pod com possível erro:', {
        name: pod.metadata?.name,
        phase: pod.status?.phase,
        initContainerStatuses: pod.status?.initContainerStatuses,
        containerStatuses: pod.status?.containerStatuses,
        conditions: pod.status?.conditions,
      });
    }

    // Verifica se há problemas com init containers primeiro
    const initContainerStatuses = pod.status?.initContainerStatuses || [];
    for (const container of initContainerStatuses) {
      // Qualquer estado de waiting indica problema
      if (container.state?.waiting?.reason) {
        const { reason, message } = container.state.waiting;

        // Casos específicos
        let displayText = 'Erro (Init)';
        if (reason.includes('Image')) {
          displayText = 'Erro de Imagem (Init)';
        } else if (
          reason.includes('Config') ||
          reason.includes('InvalidImageName')
        ) {
          displayText = 'Erro Config (Init)';
        } else if (reason.includes('Crash')) {
          displayText = 'Crash Loop (Init)';
        } else if (reason.includes('Pull')) {
          displayText = 'Erro Pull (Init)';
        }

        return {
          text: displayText,
          color: 'text-red-600',
          title: `${reason}: ${message || 'Erro no init container'}`,
          containerName: container.name,
          isInitContainer: true,
        };
      }

      // Container terminado com erro
      if (
        container.state?.terminated?.reason &&
        container.state.terminated.exitCode !== 0
      ) {
        return {
          text: 'Terminado (Init)',
          color: 'text-red-600',
          title: `${container.state.terminated.reason}: Exit code ${container.state.terminated.exitCode}`,
          containerName: container.name,
          isInitContainer: true,
        };
      }

      // Se não está ready e não tem estado waiting/terminated, pode estar com problema
      if (!container.ready && !container.state?.running) {
        return {
          text: 'Não Ready (Init)',
          color: 'text-yellow-600',
          title: `Init container ${container.name} não está pronto`,
          containerName: container.name,
          isInitContainer: true,
        };
      }
    }

    // Verifica se há problemas com containers normais
    const containerStatuses = pod.status?.containerStatuses || [];
    for (const container of containerStatuses) {
      // Qualquer estado de waiting indica problema
      if (container.state?.waiting?.reason) {
        const { reason, message } = container.state.waiting;

        // Casos específicos
        let displayText = 'Erro';
        if (reason.includes('Image')) {
          displayText = 'Erro de Imagem';
        } else if (
          reason.includes('Config') ||
          reason.includes('InvalidImageName')
        ) {
          displayText = 'Erro Config';
        } else if (reason.includes('Crash')) {
          displayText = 'Crash Loop';
        } else if (reason.includes('Pull')) {
          displayText = 'Erro Pull';
        }

        return {
          text: displayText,
          color: 'text-red-600',
          title: `${reason}: ${message || 'Erro no container'}`,
          containerName: container.name,
          isInitContainer: false,
        };
      }

      // Container terminado com erro
      if (
        container.state?.terminated?.reason &&
        container.state.terminated.exitCode !== 0
      ) {
        return {
          text: 'Terminado',
          color: 'text-red-600',
          title: `${container.state.terminated.reason}: Exit code ${container.state.terminated.exitCode}`,
          containerName: container.name,
          isInitContainer: false,
        };
      }

      // Se não está ready e não está rodando, pode estar com problema
      if (!container.ready && !container.state?.running) {
        return {
          text: 'Não Ready',
          color: 'text-yellow-600',
          title: `Container ${container.name} não está pronto`,
          containerName: container.name,
          isInitContainer: false,
        };
      }
    }

    // Verifica condições do pod
    const conditions = pod.status?.conditions || [];
    const readyCondition = conditions.find((c: any) => c.type === 'Ready');

    if (readyCondition?.status === 'False' && readyCondition?.reason) {
      return {
        text: readyCondition.reason,
        color: 'text-yellow-600',
        title: readyCondition.message || readyCondition.reason,
      };
    }

    // Pod normal
    if (pod.status?.phase === 'Running') {
      return {
        text: '-',
        color: 'text-gray-400',
        title: 'Pod funcionando normalmente',
      };
    }

    if (pod.status?.phase === 'Pending') {
      return {
        text: 'Iniciando',
        color: 'text-blue-600',
        title: 'Pod sendo inicializado',
      };
    }

    return { text: '-', color: 'text-gray-400', title: '' };
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <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">
              {deploymentName}
            </h1>
            <p className="text-muted-foreground">
              Deployment no namespace {namespaceName}
            </p>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin" />
          <span className="ml-2">Carregando detalhes do deployment...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <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">
              {deploymentName}
            </h1>
            <p className="text-muted-foreground">
              Deployment no namespace {namespaceName}
            </p>
          </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 deployment
            </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>
    );
  }

  if (!deploymentInfo) {
    return (
      <div className="space-y-6">
        <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">
              Deployment não encontrado
            </h1>
          </div>
        </div>
      </div>
    );
  }

  const deploymentStatus = getDeploymentStatus();
  const readyReplicas = deploymentInfo.status?.readyReplicas || 0;
  const replicas = deploymentInfo.spec?.replicas || 0;
  const availableReplicas = deploymentInfo.status?.availableReplicas || 0;

  return (
    <TooltipProvider>
      <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">
                <Layers className="h-8 w-8 mr-3 text-blue-600" />
                {deploymentName}
              </h1>
              <div className="text-muted-foreground">
                Deployment no namespace{' '}
                <Badge variant="outline">{namespaceName}</Badge>
              </div>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            {/* Split button - Live/Manual com dropdown de tempo */}
            <div className="flex">
              {/* Botão principal - Play/Pause */}
              <Button
                onClick={() => setAutoRefresh(!autoRefresh)}
                variant="ghost"
                className="rounded-r-none border-r-0 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                title={
                  autoRefresh
                    ? 'Pausar atualização automática'
                    : 'Ativar atualização automática'
                }
              >
                {autoRefresh ? (
                  <>
                    <Pause className="h-4 w-4 mr-2" />
                    Live ({deploymentRefreshInterval / 1000}s)
                  </>
                ) : (
                  <>
                    <Play className="h-4 w-4 mr-2" />
                    Atualizar
                  </>
                )}
              </Button>

              {/* Dropdown de tempo */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    className="rounded-l-none px-2 h-10 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                    title="Configurar intervalo de refresh"
                  >
                    <ChevronDown className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel>Intervalo de Refresh</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    onClick={() => setDeploymentRefreshInterval(1000)}
                    className={
                      deploymentRefreshInterval === 1000 ? 'bg-green-100' : ''
                    }
                  >
                    1 segundo
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setDeploymentRefreshInterval(3000)}
                    className={
                      deploymentRefreshInterval === 3000 ? 'bg-green-100' : ''
                    }
                  >
                    3 segundos
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setDeploymentRefreshInterval(5000)}
                    className={
                      deploymentRefreshInterval === 5000 ? 'bg-green-100' : ''
                    }
                  >
                    5 segundos
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setDeploymentRefreshInterval(10000)}
                    className={
                      deploymentRefreshInterval === 10000 ? 'bg-green-100' : ''
                    }
                  >
                    10 segundos
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </div>

        {/* Overview Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Status</CardTitle>
              <Activity className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <Badge
                variant={deploymentStatus.variant}
                className={deploymentStatus.color || ''}
              >
                {deploymentStatus.status}
              </Badge>
              <p className="text-xs text-muted-foreground mt-1">Estado atual</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Réplicas</CardTitle>
              <Container className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {readyReplicas}/{replicas}
              </div>
              {deploymentInfo.status?.updatedReplicas !== undefined &&
                deploymentInfo.status.updatedReplicas < replicas && (
                  <p className="text-xs text-blue-600 font-medium">
                    {deploymentInfo.status.updatedReplicas} updated
                  </p>
                )}
              <p className="text-xs text-muted-foreground">Ready/Desired</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Disponíveis</CardTitle>
              <CheckCircle className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{availableReplicas}</div>
              <p className="text-xs text-muted-foreground">
                Available replicas
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Idade</CardTitle>
              <Calendar className="h-4 w-4 text-orange-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {getAge(deploymentInfo.metadata?.creationTimestamp || '')}
              </div>
              <p className="text-xs text-muted-foreground">
                {new Date(
                  deploymentInfo.metadata?.creationTimestamp || '',
                ).toLocaleDateString('pt-BR')}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Escalar</CardTitle>
              <ArrowUpDown className="h-4 w-4 text-indigo-600" />
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-center space-x-2">
                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={async () => {
                    const newValue = Math.max(replicas - 1, 0);
                    setScaling(true);
                    try {
                      const command = `kubectl scale deployment ${deploymentName} --replicas=${newValue} -n ${namespaceName}`;
                      const result = await executeCommand(command);

                      if (result.success) {
                        showToast({
                          title: 'Deployment Escalado',
                          description: `Escalado para ${newValue} réplica(s)`,
                          variant: 'success',
                        });
                        await refetch();
                      } else {
                        showToast({
                          title: 'Erro ao Escalar',
                          description:
                            result.error || 'Falha ao escalar deployment',
                          variant: 'destructive',
                        });
                      }
                    } catch (err) {
                      showToast({
                        title: 'Erro',
                        description: 'Erro inesperado ao escalar',
                        variant: 'destructive',
                      });
                    } finally {
                      setScaling(false);
                    }
                  }}
                  disabled={replicas <= 0 || scaling}
                >
                  {scaling ? (
                    <Loader2 className="h-3 w-3 animate-spin" />
                  ) : (
                    <Minus className="h-3 w-3" />
                  )}
                </Button>

                <div className="text-xl font-bold min-w-[2rem] text-center">
                  {scaling ? (
                    <Loader2 className="h-4 w-4 animate-spin mx-auto" />
                  ) : (
                    replicas
                  )}
                </div>

                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={async () => {
                    const newValue = Math.min(replicas + 1, 100);
                    setScaling(true);
                    try {
                      const command = `kubectl scale deployment ${deploymentName} --replicas=${newValue} -n ${namespaceName}`;
                      const result = await executeCommand(command);

                      if (result.success) {
                        showToast({
                          title: 'Deployment Escalado',
                          description: `Escalado para ${newValue} réplica(s)`,
                          variant: 'success',
                        });
                        await refetch();
                      } else {
                        showToast({
                          title: 'Erro ao Escalar',
                          description:
                            result.error || 'Falha ao escalar deployment',
                          variant: 'destructive',
                        });
                      }
                    } catch (err) {
                      showToast({
                        title: 'Erro',
                        description: 'Erro inesperado ao escalar',
                        variant: 'destructive',
                      });
                    } finally {
                      setScaling(false);
                    }
                  }}
                  disabled={replicas >= 100 || scaling}
                >
                  {scaling ? (
                    <Loader2 className="h-3 w-3 animate-spin" />
                  ) : (
                    <Plus className="h-3 w-3" />
                  )}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground text-center mt-1">
                Réplicas
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Deployment Configuration */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center">
                <Settings className="h-5 w-5 mr-2" />
                Configuração do Deployment
              </CardTitle>
              <div className="flex gap-2">
                <Button onClick={handleScale} variant="outline" size="sm">
                  <ArrowUpDown className="h-4 w-4 mr-2" />
                  Escalar
                </Button>
                <Button
                  onClick={handleRestart}
                  variant="outline"
                  size="sm"
                  disabled={restarting || !pods || pods.length === 0}
                >
                  <RotateCcw
                    className={`h-4 w-4 mr-2 ${restarting ? 'animate-spin' : ''}`}
                  />
                  {restarting ? 'Reiniciando...' : 'Restart'}
                </Button>
                <Button variant="outline" size="sm" disabled>
                  <Terminal className="h-4 w-4 mr-2" />
                  Terminal
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    // Se houver pods, pega o primeiro pod running
                    const runningPod = pods.find(
                      (pod: any) => pod.status?.phase === 'Running',
                    );
                    const podToUse = runningPod || pods[0];
                    if (podToUse) {
                      handlePodLogs(podToUse);
                    } else {
                      showToast({
                        title: 'Nenhum Pod Encontrado',
                        description:
                          'Não há pods disponíveis para visualizar logs',
                        variant: 'destructive',
                      });
                    }
                  }}
                  disabled={!pods || pods.length === 0}
                >
                  <FileText className="h-4 w-4 mr-2" />
                  Logs
                </Button>
                <Button onClick={handleYamlView} variant="outline" size="sm">
                  <Eye className="h-4 w-4 mr-2" />
                  YAML
                </Button>
                <Button
                  onClick={handleDeleteDeploymentClick}
                  variant="destructive"
                  size="sm"
                >
                  <Trash className="h-4 w-4 mr-2" />
                  Excluir
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <Tabs
              value={activeTab}
              onValueChange={handleTabChange}
              className="w-full"
            >
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="configuracoes">Configurações</TabsTrigger>
                <TabsTrigger value="configmap">ConfigMap</TabsTrigger>
                <TabsTrigger value="secret">Secret</TabsTrigger>
                <TabsTrigger value="service">Service</TabsTrigger>
              </TabsList>

              <TabsContent value="configuracoes" className="mt-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-12">
                  {/* Coluna 1: Informações Básicas */}
                  <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                    <div className="flex justify-between items-start min-h-[20px]">
                      <span className="text-sm text-muted-foreground font-medium">
                        Nome:
                      </span>
                      <span className="text-sm font-semibold text-right ml-4">
                        {deploymentInfo.metadata?.name}
                      </span>
                    </div>
                    <div className="flex justify-between items-start min-h-[20px]">
                      <span className="text-sm text-muted-foreground font-medium">
                        Estratégia:
                      </span>
                      <span className="text-sm font-semibold text-right ml-4">
                        {deploymentInfo.spec?.strategy?.type || 'RollingUpdate'}
                      </span>
                    </div>
                  </div>

                  {/* Coluna 2: Configurações de Imagem */}
                  <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                    <div className="flex justify-between items-start min-h-[20px] group">
                      <span className="text-sm text-muted-foreground font-medium">
                        Service Account:
                      </span>
                      {!isEditingServiceAccount ? (
                        <div className="flex items-center">
                          <span className="text-sm font-semibold text-right ml-4">
                            {deploymentInfo.spec?.template?.spec
                              ?.serviceAccountName || 'default'}
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={handleEditServiceAccount}
                          >
                            <Edit3 className="h-3 w-3" />
                          </Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 ml-4">
                          <Select
                            value={selectedServiceAccount}
                            onValueChange={setSelectedServiceAccount}
                            disabled={updatingServiceAccount}
                          >
                            <SelectTrigger className="w-[200px] h-8">
                              <SelectValue placeholder="Selecionar service account..." />
                            </SelectTrigger>
                            <SelectContent>
                              {availableServiceAccounts.map((serviceAccount) => (
                                <SelectItem key={serviceAccount.metadata.name} value={serviceAccount.metadata.name}>
                                  {serviceAccount.metadata.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleSaveServiceAccount}
                            disabled={updatingServiceAccount}
                          >
                            {updatingServiceAccount ? (
                              <Loader2 className="h-3 w-3 animate-spin" />
                            ) : (
                              <Check className="h-3 w-3 text-green-600" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleCancelEditServiceAccount}
                            disabled={updatingServiceAccount}
                          >
                            <X className="h-3 w-3 text-red-600" />
                          </Button>
                        </div>
                      )}
                    </div>
                    <div className="flex justify-between items-start min-h-[20px] group">
                      <span className="text-sm text-muted-foreground font-medium">
                        Pull Secret:
                      </span>
                      {!isEditingPullSecret ? (
                        <div className="flex items-center">
                          <span className="text-sm font-semibold text-right ml-4">
                            {deploymentInfo.spec?.template?.spec?.imagePullSecrets
                              ?.length > 0
                              ? deploymentInfo.spec.template.spec.imagePullSecrets
                                  .map((s: any) => s.name)
                                  .join(', ')
                              : 'Nenhum'}
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={handleEditPullSecret}
                          >
                            <Edit3 className="h-3 w-3" />
                          </Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 ml-4">
                          <Select
                            value={selectedPullSecret}
                            onValueChange={setSelectedPullSecret}
                            disabled={updatingPullSecret}
                          >
                            <SelectTrigger className="w-[200px] h-8">
                              <SelectValue placeholder="Selecionar secret..." />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">Nenhum</SelectItem>
                              {availableSecrets.map((secret) => (
                                <SelectItem key={secret.metadata.name} value={secret.metadata.name}>
                                  {secret.metadata.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleSavePullSecret}
                            disabled={updatingPullSecret}
                          >
                            {updatingPullSecret ? (
                              <Loader2 className="h-3 w-3 animate-spin" />
                            ) : (
                              <Check className="h-3 w-3 text-green-600" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleCancelEditPullSecret}
                            disabled={updatingPullSecret}
                          >
                            <X className="h-3 w-3 text-red-600" />
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Coluna 3: Políticas */}
                  <div className="space-y-5">
                    <div className="flex justify-between items-start min-h-[20px] group">
                      <span className="text-sm text-muted-foreground font-medium">
                        Restart Policy:
                      </span>
                      {!isEditingRestartPolicy ? (
                        <div className="flex items-center">
                          <span className="text-sm font-semibold text-right ml-4">
                            {deploymentInfo.spec?.template?.spec?.restartPolicy ||
                              'Always'}
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={handleEditRestartPolicy}
                          >
                            <Edit3 className="h-3 w-3" />
                          </Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 ml-4">
                          <Select
                            value={selectedRestartPolicy}
                            onValueChange={setSelectedRestartPolicy}
                            disabled={updatingRestartPolicy}
                          >
                            <SelectTrigger className="w-[130px] h-8">
                              <SelectValue placeholder="Selecionar policy..." />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Always">Always</SelectItem>
                            </SelectContent>
                          </Select>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleSaveRestartPolicy}
                            disabled={updatingRestartPolicy}
                          >
                            {updatingRestartPolicy ? (
                              <Loader2 className="h-3 w-3 animate-spin" />
                            ) : (
                              <Check className="h-3 w-3 text-green-600" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleCancelEditRestartPolicy}
                            disabled={updatingRestartPolicy}
                          >
                            <X className="h-3 w-3 text-red-600" />
                          </Button>
                        </div>
                      )}
                    </div>
                    <div className="flex justify-between items-start min-h-[20px] group">
                      <span className="text-sm text-muted-foreground font-medium">
                        Image Pull Policy:
                      </span>
                      {!isEditingImagePullPolicy ? (
                        <div className="flex items-center">
                          <span className="text-sm font-semibold text-right ml-4">
                            {deploymentInfo.spec?.template?.spec?.containers?.[0]?.imagePullPolicy ||
                              'IfNotPresent'}
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity"
                            onClick={handleEditImagePullPolicy}
                          >
                            <Edit3 className="h-3 w-3" />
                          </Button>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 ml-4">
                          <Select
                            value={selectedImagePullPolicy}
                            onValueChange={setSelectedImagePullPolicy}
                            disabled={updatingImagePullPolicy}
                          >
                            <SelectTrigger className="w-[150px] h-8">
                              <SelectValue placeholder="Selecionar policy..." />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="Always">Always</SelectItem>
                              <SelectItem value="IfNotPresent">IfNotPresent</SelectItem>
                              <SelectItem value="Never">Never</SelectItem>
                            </SelectContent>
                          </Select>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleSaveImagePullPolicy}
                            disabled={updatingImagePullPolicy}
                          >
                            {updatingImagePullPolicy ? (
                              <Loader2 className="h-3 w-3 animate-spin" />
                            ) : (
                              <Check className="h-3 w-3 text-green-600" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={handleCancelEditImagePullPolicy}
                            disabled={updatingImagePullPolicy}
                          >
                            <X className="h-3 w-3 text-red-600" />
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Labels Section */}
                <div className="mt-6 pt-4 border-t">
                  <h4 className="font-medium text-sm text-muted-foreground mb-2">
                    Labels
                  </h4>
                  <div className="flex flex-wrap gap-1">
                    {Object.entries(deploymentInfo.metadata?.labels || {})
                      .length > 0 ? (
                      Object.entries(deploymentInfo.metadata?.labels || {}).map(
                        ([key, value]) => (
                          <div key={key} className="group relative">
                            <Badge
                              variant="secondary"
                              className="text-xs pr-1"
                            >
                              {key}: {value}
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-4 w-4 p-0 ml-1 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-100"
                                onClick={() => handleDeleteLabel(key)}
                                disabled={deletingLabel === key}
                              >
                                {deletingLabel === key ? (
                                  <Loader2 className="h-2 w-2 animate-spin" />
                                ) : (
                                  <X className="h-2 w-2 text-red-600" />
                                )}
                              </Button>
                            </Badge>
                          </div>
                        ),
                      )
                    ) : (
                      <span className="text-sm text-muted-foreground">
                        Nenhum label definido
                      </span>
                    )}
                  </div>
                </div>

                {/* Annotations Section */}
                <div className="mt-4">
                  <h4 className="font-medium text-sm text-muted-foreground mb-2">
                    Annotations
                  </h4>
                  <div className="flex flex-wrap gap-1">
                    {Object.entries(deploymentInfo.metadata?.annotations || {})
                      .length > 0 ? (
                      Object.entries(
                        deploymentInfo.metadata?.annotations || {},
                      ).map(([key, value]) => (
                        <div key={key} className="group relative">
                          <Badge variant="outline" className="text-xs pr-1">
                            {key}:{' '}
                            {typeof value === 'string' && value.length > 50
                              ? `${value.substring(0, 50)}...`
                              : value}
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-4 w-4 p-0 ml-1 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-100"
                              onClick={() => handleDeleteAnnotation(key)}
                              disabled={deletingAnnotation === key}
                            >
                              {deletingAnnotation === key ? (
                                <Loader2 className="h-2 w-2 animate-spin" />
                              ) : (
                                <X className="h-2 w-2 text-red-600" />
                              )}
                            </Button>
                          </Badge>
                        </div>
                      ))
                    ) : (
                      <span className="text-sm text-muted-foreground">
                        Nenhuma annotation definida
                      </span>
                    )}
                  </div>
                </div>

                {/* Containers Section */}
                <div className="mt-6 pt-4 border-t">
                  <h4 className="font-medium text-sm text-muted-foreground mb-3">
                    Containers
                  </h4>
                  <div className="overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Nome
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Imagem
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Portas
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Tipo
                          </TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {/* Init Containers */}
                        {deploymentInfo.spec?.template?.spec?.initContainers?.map(
                          (container: any, index: number) => (
                            <TableRow
                              key={`init-${index}`}
                              className="hover:bg-muted/50 h-10"
                            >
                              <TableCell className="font-medium py-2">
                                <div className="flex items-center space-x-1.5">
                                  <Container className="h-3.5 w-3.5 text-orange-600" />
                                  <span className="text-xs">
                                    {container.name}
                                  </span>
                                </div>
                              </TableCell>
                              <TableCell className="py-2 group">
                                {editingContainerImage?.containerType === 'init' && editingContainerImage?.containerIndex === index ? (
                                  <div className="flex items-center gap-2">
                                    <Input
                                      value={editingImageValue}
                                      onChange={(e) => setEditingImageValue(e.target.value)}
                                      className="font-mono text-xs h-7 flex-1 min-w-0"
                                      disabled={updatingContainerImage}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                          handleSaveContainerImage();
                                        } else if (e.key === 'Escape') {
                                          handleCancelEditContainerImage();
                                        }
                                      }}
                                      autoFocus
                                    />
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-6 w-6 p-0"
                                      onClick={handleSaveContainerImage}
                                      disabled={updatingContainerImage || !editingImageValue.trim()}
                                    >
                                      {updatingContainerImage ? (
                                        <Loader2 className="h-3 w-3 animate-spin" />
                                      ) : (
                                        <Check className="h-3 w-3 text-green-600" />
                                      )}
                                    </Button>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-6 w-6 p-0"
                                      onClick={handleCancelEditContainerImage}
                                      disabled={updatingContainerImage}
                                    >
                                      <X className="h-3 w-3 text-red-600" />
                                    </Button>
                                  </div>
                                ) : (
                                  <div className="flex items-center min-w-0 w-full">
                                    <div className="flex items-center min-w-0 max-w-fit">
                                      <span
                                        className="font-mono text-xs truncate block"
                                        title={container.image}
                                      >
                                        {container.image}
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
                                        onClick={() => handleEditContainerImage(index, 'init', container.image)}
                                      >
                                        <Edit3 className="h-3 w-3" />
                                      </Button>
                                    </div>
                                  </div>
                                )}
                              </TableCell>
                              <TableCell className="py-2">
                                <div className="flex flex-wrap gap-0.5">
                                  {container.ports?.length > 0 ? (
                                    container.ports.map(
                                      (port: any, portIndex: number) => (
                                        <Badge
                                          key={portIndex}
                                          variant="outline"
                                          className="text-xs px-1.5 py-0.5 h-5"
                                        >
                                          {port.containerPort}/
                                          {port.protocol || 'TCP'}
                                        </Badge>
                                      ),
                                    )
                                  ) : (
                                    <span className="text-xs text-muted-foreground">
                                      -
                                    </span>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="py-2">
                                <Badge
                                  variant="secondary"
                                  className="text-xs bg-orange-100 text-orange-800 px-2 py-0.5 h-5"
                                >
                                  Init
                                </Badge>
                              </TableCell>
                            </TableRow>
                          ),
                        ) || []}

                        {/* Regular Containers */}
                        {deploymentInfo.spec?.template?.spec?.containers?.map(
                          (container: any, index: number) => (
                            <TableRow
                              key={`regular-${index}`}
                              className="hover:bg-muted/50 h-10"
                            >
                              <TableCell className="font-medium py-2">
                                <div className="flex items-center space-x-1.5">
                                  <Container className="h-3.5 w-3.5 text-purple-600" />
                                  <span className="text-xs">
                                    {container.name}
                                  </span>
                                </div>
                              </TableCell>
                              <TableCell className="py-2 group">
                                {editingContainerImage?.containerType === 'regular' && editingContainerImage?.containerIndex === index ? (
                                  <div className="flex items-center gap-2">
                                    <Input
                                      value={editingImageValue}
                                      onChange={(e) => setEditingImageValue(e.target.value)}
                                      className="font-mono text-xs h-7 flex-1 min-w-0"
                                      disabled={updatingContainerImage}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                          handleSaveContainerImage();
                                        } else if (e.key === 'Escape') {
                                          handleCancelEditContainerImage();
                                        }
                                      }}
                                      autoFocus
                                    />
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-6 w-6 p-0"
                                      onClick={handleSaveContainerImage}
                                      disabled={updatingContainerImage || !editingImageValue.trim()}
                                    >
                                      {updatingContainerImage ? (
                                        <Loader2 className="h-3 w-3 animate-spin" />
                                      ) : (
                                        <Check className="h-3 w-3 text-green-600" />
                                      )}
                                    </Button>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-6 w-6 p-0"
                                      onClick={handleCancelEditContainerImage}
                                      disabled={updatingContainerImage}
                                    >
                                      <X className="h-3 w-3 text-red-600" />
                                    </Button>
                                  </div>
                                ) : (
                                  <div className="flex items-center min-w-0 w-full">
                                    <div className="flex items-center min-w-0 max-w-fit">
                                      <span
                                        className="font-mono text-xs truncate block"
                                        title={container.image}
                                      >
                                        {container.image}
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        className="h-6 w-6 p-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
                                        onClick={() => handleEditContainerImage(index, 'regular', container.image)}
                                      >
                                        <Edit3 className="h-3 w-3" />
                                      </Button>
                                    </div>
                                  </div>
                                )}
                              </TableCell>
                              <TableCell className="py-2">
                                <div className="flex flex-wrap gap-0.5">
                                  {container.ports?.length > 0 ? (
                                    container.ports.map(
                                      (port: any, portIndex: number) => (
                                        <Badge
                                          key={portIndex}
                                          variant="outline"
                                          className="text-xs px-1.5 py-0.5 h-5"
                                        >
                                          {port.containerPort}/
                                          {port.protocol || 'TCP'}
                                        </Badge>
                                      ),
                                    )
                                  ) : (
                                    <span className="text-xs text-muted-foreground">
                                      -
                                    </span>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="py-2">
                                <Badge
                                  variant="outline"
                                  className="text-xs px-2 py-0.5 h-5"
                                >
                                  Regular
                                </Badge>
                              </TableCell>
                            </TableRow>
                          ),
                        ) || []}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="configmap" className="mt-6">
                {loadingConfigMaps ? (
                  <div className="text-center py-8">
                    <Loader2 className="h-8 w-8 mx-auto text-muted-foreground animate-spin mb-4" />
                    <p className="text-muted-foreground">
                      Carregando ConfigMaps...
                    </p>
                  </div>
                ) : configMaps.length === 0 ? (
                  <div className="text-center py-8">
                    <Database className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="text-lg font-medium mb-2">
                      Nenhum ConfigMap Relacionado
                    </h3>
                    <p className="text-muted-foreground mb-4">
                      Este deployment não possui ConfigMaps associados.
                    </p>
                    <Badge variant="outline">Nenhum configmap encontrado</Badge>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-medium">
                        ConfigMaps Relacionados ({configMaps.length})
                      </h3>
                    </div>

                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Nome
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Chaves
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Uso
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Tamanho
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8">
                            Idade
                          </TableHead>
                          <TableHead className="text-xs font-medium py-2 h-8 text-right">
                            Ações
                          </TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {configMaps.map((configMap: any, index: number) => {
                          const configMapInfo = getConfigMapInfo(configMap);
                          const { usageEntry } = configMap;

                          return (
                            <TableRow key={index} className="hover:bg-muted/50">
                              <TableCell className="font-medium py-2">
                                <div className="flex items-center space-x-2">
                                  <Database className="h-4 w-4 text-blue-600" />
                                  <span className="cursor-pointer hover:text-blue-600 transition-colors hover:underline">
                                    {configMap.metadata?.name}
                                  </span>
                                  <Copy
                                    className="h-4 w-4 cursor-pointer hover:text-blue-600 flex-shrink-0"
                                    onClick={() => {
                                      navigator.clipboard.writeText(
                                        configMap.metadata?.name || '',
                                      );
                                      showToast({
                                        title: 'Nome Copiado',
                                        description: `Nome "${configMap.metadata?.name}" copiado para a área de transferência`,
                                        variant: 'success',
                                      });
                                    }}
                                  />
                                </div>
                              </TableCell>
                              <TableCell className="py-2">
                                <div className="flex items-center space-x-2">
                                  {usageEntry.isFullConfigMap ? (
                                    <Badge
                                      variant="outline"
                                      className="text-xs bg-green-50 text-green-700 cursor-pointer hover:bg-opacity-80"
                                      onClick={() =>
                                        handleConfigMapKeysView(configMap)
                                      }
                                    >
                                      (Todas as Chaves)
                                    </Badge>
                                  ) : usageEntry.keys.length > 0 ? (
                                    <div className="flex flex-wrap gap-1">
                                      {usageEntry.keys.map((key: string) => (
                                        <Badge
                                          key={key}
                                          variant="outline"
                                          className="text-xs bg-blue-50 text-blue-700 cursor-pointer hover:bg-opacity-80"
                                          onClick={() =>
                                            handleConfigMapKeysView(configMap)
                                          }
                                        >
                                          {key}
                                        </Badge>
                                      ))}
                                    </div>
                                  ) : (
                                    <Badge
                                      variant="outline"
                                      className="text-xs"
                                    >
                                      (Não especificado)
                                    </Badge>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell className="py-2">
                                <Badge
                                  variant="secondary"
                                  className="text-xs px-1.5 py-0.5 h-5"
                                >
                                  {usageEntry.usageType}
                                </Badge>
                              </TableCell>
                              <TableCell className="py-2">
                                <span className="text-xs text-muted-foreground">
                                  {(configMapInfo.size / 1024).toFixed(1)} KB
                                </span>
                              </TableCell>
                              <TableCell className="py-2">
                                <span className="text-xs text-muted-foreground">
                                  {getAge(
                                    configMap.metadata?.creationTimestamp || '',
                                  )}
                                </span>
                              </TableCell>
                              <TableCell className="py-2 text-right">
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="sm">
                                      <MoreVertical className="h-4 w-4" />
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent align="end">
                                    <DropdownMenuLabel>Ações</DropdownMenuLabel>
                                    <DropdownMenuItem
                                      onClick={() => {
                                        // Implementar visualização das chaves do configmap
                                        showToast({
                                          title: 'Em Desenvolvimento',
                                          description:
                                            'Visualização das chaves do configmap será implementada em breve',
                                          variant: 'default',
                                        });
                                      }}
                                    >
                                      <Eye className="h-4 w-4 mr-2" />
                                      Ver Chaves
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                      onClick={() => {
                                        setSelectedConfigMapName(
                                          configMap.metadata?.name || '',
                                        );
                                        setConfigMapYamlModalOpen(true);
                                      }}
                                    >
                                      <FileText className="h-4 w-4 mr-2" />
                                      Ver YAML
                                    </DropdownMenuItem>
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem className="text-red-600">
                                      <Trash2 className="h-4 w-4 mr-2" />
                                      Excluir ConfigMap
                                    </DropdownMenuItem>
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="secret" className="mt-6">
                {loadingSecrets ? (
                  <div className="text-center py-8">
                    <Loader2 className="h-8 w-8 mx-auto text-muted-foreground animate-spin mb-4" />
                    <p className="text-muted-foreground">
                      Carregando Secrets...
                    </p>
                  </div>
                ) : secrets.length === 0 ? (
                  <div className="text-center py-8">
                    <Shield className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="text-lg font-medium mb-2">
                      Nenhum Secret Relacionado
                    </h3>
                    <p className="text-muted-foreground mb-4">
                      Este deployment não referencia nenhum Secret.
                    </p>
                    <Badge variant="outline">Nenhum secret encontrado</Badge>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-medium">
                        Secrets Relacionados ({secrets.length})
                      </h3>
                    </div>

                    <div className="overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Nome
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Tipo
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Chaves
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Uso
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Idade
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8 text-right">
                              Ações
                            </TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {secrets.map((secret: any, index: number) => {
                            const secretInfo = getSecretInfo(secret);
                            const SecretIcon = secretInfo.icon;
                            const { usageEntry } = secret;

                            return (
                              <TableRow
                                key={index}
                                className="hover:bg-muted/50"
                              >
                                <TableCell className="font-medium py-2">
                                  <div className="flex items-center space-x-2">
                                    <SecretIcon className="h-4 w-4 text-orange-600" />
                                    <span className="cursor-pointer hover:text-blue-600 transition-colors hover:underline">
                                      {secret.metadata?.name}
                                    </span>
                                    <Copy
                                      className="h-4 w-4 cursor-pointer hover:text-blue-600 flex-shrink-0"
                                      onClick={() => {
                                        navigator.clipboard.writeText(
                                          secret.metadata?.name || '',
                                        );
                                        showToast({
                                          title: 'Nome Copiado',
                                          description: `Nome "${secret.metadata?.name}" copiado para a área de transferência`,
                                          variant: 'success',
                                        });
                                      }}
                                    />
                                  </div>
                                </TableCell>
                                <TableCell className="py-2">
                                  <Badge
                                    variant={secretInfo.variant as any}
                                    className="text-xs"
                                  >
                                    {secretInfo.type.replace(
                                      'kubernetes.io/',
                                      '',
                                    )}
                                  </Badge>
                                </TableCell>
                                <TableCell className="py-2">
                                  <div className="flex items-center space-x-2">
                                    {(() => {
                                      const keyDisplay = getSecretKeysDisplay(
                                        secret,
                                        usageEntry,
                                      );

                                      if (keyDisplay.type === 'special') {
                                        const secretType =
                                          secret.type || 'Opaque';
                                        const isDockerConfig =
                                          secretType ===
                                          'kubernetes.io/dockerconfigjson';

                                        return (
                                          <TooltipProvider>
                                            <Tooltip>
                                              <TooltipTrigger asChild>
                                                <Badge
                                                  variant="outline"
                                                  className={`text-xs ${isDockerConfig ? 'cursor-pointer hover:bg-opacity-80' : 'cursor-help'} ${keyDisplay.color}`}
                                                  onClick={
                                                    isDockerConfig
                                                      ? () =>
                                                          handleDockerConfigView(
                                                            secret,
                                                          )
                                                      : undefined
                                                  }
                                                >
                                                  {keyDisplay.badge}
                                                </Badge>
                                              </TooltipTrigger>
                                              <TooltipContent>
                                                <div className="text-xs">
                                                  {keyDisplay.tooltip}
                                                  {isDockerConfig && (
                                                    <p className="mt-1 text-blue-600">
                                                      Clique para ver detalhes
                                                    </p>
                                                  )}
                                                </div>
                                              </TooltipContent>
                                            </Tooltip>
                                          </TooltipProvider>
                                        );
                                      }
                                      if (keyDisplay.type === 'all-keys') {
                                        return (
                                          <Badge
                                            variant="outline"
                                            className={`text-xs cursor-pointer hover:bg-opacity-80 ${keyDisplay.color}`}
                                            onClick={() =>
                                              handleSecretKeysView(secret)
                                            }
                                          >
                                            (Todas as Chaves)
                                          </Badge>
                                        );
                                      }
                                      if (keyDisplay.type === 'specific-keys') {
                                        return (
                                          <div className="flex flex-wrap gap-1">
                                            {keyDisplay.keys.map(
                                              (key: string) => (
                                                <Badge
                                                  key={key}
                                                  variant="outline"
                                                  className={`text-xs cursor-pointer hover:bg-opacity-80 ${keyDisplay.color}`}
                                                  onClick={() =>
                                                    handleSecretKeysView(secret)
                                                  }
                                                >
                                                  {key}
                                                </Badge>
                                              ),
                                            )}
                                          </div>
                                        );
                                      }
                                      return (
                                        <Badge
                                          variant="outline"
                                          className="text-xs"
                                        >
                                          (Não especificado)
                                        </Badge>
                                      );
                                    })()}
                                  </div>
                                </TableCell>
                                <TableCell className="py-2">
                                  <Badge
                                    variant="secondary"
                                    className="text-xs px-1.5 py-0.5 h-5"
                                  >
                                    {usageEntry.usageType}
                                  </Badge>
                                </TableCell>
                                <TableCell className="py-2">
                                  <span className="text-xs text-muted-foreground">
                                    {getAge(
                                      secret.metadata?.creationTimestamp || '',
                                    )}
                                  </span>
                                </TableCell>
                                <TableCell className="py-2 text-right">
                                  <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                      <Button variant="ghost" size="sm">
                                        <MoreVertical className="h-4 w-4" />
                                      </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end">
                                      <DropdownMenuLabel>
                                        Ações
                                      </DropdownMenuLabel>
                                      <DropdownMenuItem
                                        onClick={() => {
                                          // Implementar visualização das chaves do secret
                                          showToast({
                                            title: 'Em Desenvolvimento',
                                            description:
                                              'Visualização das chaves do secret será implementada em breve',
                                            variant: 'default',
                                          });
                                        }}
                                      >
                                        <Eye className="h-4 w-4 mr-2" />
                                        Ver Chaves
                                      </DropdownMenuItem>
                                      <DropdownMenuItem
                                        onClick={() => {
                                          setSelectedSecretName(
                                            secret.metadata?.name || '',
                                          );
                                          setSecretYamlModalOpen(true);
                                        }}
                                      >
                                        <FileText className="h-4 w-4 mr-2" />
                                        Ver YAML
                                      </DropdownMenuItem>
                                      <DropdownMenuSeparator />
                                      <DropdownMenuItem className="text-red-600">
                                        <Trash2 className="h-4 w-4 mr-2" />
                                        Excluir Secret
                                      </DropdownMenuItem>
                                    </DropdownMenuContent>
                                  </DropdownMenu>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="service" className="mt-6">
                {loadingServices || refreshingServicesAfterDelete ? (
                  <div className="text-center py-8">
                    <Loader2 className="h-8 w-8 mx-auto text-muted-foreground animate-spin mb-4" />
                    <p className="text-muted-foreground">
                      {refreshingServicesAfterDelete
                        ? 'Atualizando lista de Services...'
                        : 'Carregando Services...'}
                    </p>
                  </div>
                ) : services.length === 0 ? (
                  <div className="text-center py-8">
                    <Network className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                    <h3 className="text-lg font-medium mb-2">
                      Nenhum Service Relacionado
                    </h3>
                    <p className="text-muted-foreground mb-4">
                      Este deployment não possui Services apontando para ele.
                    </p>
                    <Badge variant="outline">Nenhum service encontrado</Badge>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="text-lg font-medium">
                        Services Relacionados ({services.length})
                      </h3>
                    </div>

                    <div className="overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Nome
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Tipo
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Cluster IP
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              External IP
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Portas
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Status
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8">
                              Idade
                            </TableHead>
                            <TableHead className="text-xs font-medium py-2 h-8 text-right">
                              Ações
                            </TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {services.map((service: any, index: number) => {
                            const serviceStatus = getServiceStatus(service);
                            const StatusIcon = serviceStatus.icon;
                            const externalIP =
                              service.status?.loadBalancer?.ingress?.[0]?.ip ||
                              service.status?.loadBalancer?.ingress?.[0]
                                ?.hostname ||
                              service.spec?.externalIPs?.[0];

                            return (
                              <TableRow
                                key={index}
                                className="hover:bg-muted/50"
                              >
                                <TableCell className="font-medium py-2">
                                  <div className="flex items-center space-x-2">
                                    <Network className="h-4 w-4 text-blue-600" />
                                    <span className="cursor-pointer hover:text-blue-600 transition-colors hover:underline">
                                      {service.metadata?.name}
                                    </span>
                                    <Copy
                                      className="h-4 w-4 cursor-pointer hover:text-blue-600 flex-shrink-0"
                                      onClick={() => {
                                        navigator.clipboard.writeText(
                                          service.metadata?.name || '',
                                        );
                                        showToast({
                                          title: 'Nome Copiado',
                                          description: `Nome "${service.metadata?.name}" copiado para a área de transferência`,
                                          variant: 'success',
                                        });
                                      }}
                                    />
                                  </div>
                                </TableCell>
                                <TableCell className="py-2">
                                  <Badge variant="outline" className="text-xs">
                                    {service.spec?.type || 'ClusterIP'}
                                  </Badge>
                                </TableCell>
                                <TableCell className="py-2">
                                  <span className="font-mono text-xs">
                                    {service.spec?.clusterIP || '-'}
                                  </span>
                                </TableCell>
                                <TableCell className="py-2">
                                  <span className="font-mono text-xs">
                                    {externalIP || '-'}
                                  </span>
                                </TableCell>
                                <TableCell className="py-2">
                                  <div className="flex flex-wrap gap-1">
                                    {service.spec?.ports?.map(
                                      (port: any, portIndex: number) => (
                                        <Badge
                                          key={portIndex}
                                          variant="secondary"
                                          className="text-xs px-1.5 py-0.5 h-5"
                                        >
                                          {port.port}
                                          {port.nodePort &&
                                            `(${port.nodePort})`}
                                          /{port.protocol || 'TCP'}
                                        </Badge>
                                      ),
                                    ) || '-'}
                                  </div>
                                </TableCell>
                                <TableCell className="py-2">
                                  <div className="flex items-center space-x-1">
                                    <StatusIcon
                                      className={`h-3 w-3 ${serviceStatus.color}`}
                                    />
                                    <span
                                      className={`text-xs ${serviceStatus.color}`}
                                    >
                                      {serviceStatus.status}
                                    </span>
                                  </div>
                                </TableCell>
                                <TableCell className="py-2">
                                  <span className="text-xs text-muted-foreground">
                                    {getAge(
                                      service.metadata?.creationTimestamp || '',
                                    )}
                                  </span>
                                </TableCell>
                                <TableCell className="py-2 text-right">
                                  <DropdownMenu>
                                    <DropdownMenuTrigger asChild>
                                      <Button variant="ghost" size="sm">
                                        <MoreVertical className="h-4 w-4" />
                                      </Button>
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end">
                                      <DropdownMenuLabel>
                                        Ações
                                      </DropdownMenuLabel>
                                      <DropdownMenuItem
                                        onClick={() => {
                                          setSelectedServiceName(
                                            service.metadata?.name || '',
                                          );
                                          setServiceYamlModalOpen(true);
                                        }}
                                      >
                                        <Eye className="h-4 w-4 mr-2" />
                                        Ver YAML
                                      </DropdownMenuItem>
                                      <DropdownMenuSeparator />
                                      <DropdownMenuItem
                                        className="text-red-600"
                                        onClick={() =>
                                          handleDeleteServiceClick(service)
                                        }
                                      >
                                        <Trash2 className="h-4 w-4 mr-2" />
                                        Excluir Service
                                      </DropdownMenuItem>
                                    </DropdownMenuContent>
                                  </DropdownMenu>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        {/* Pods Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center">
                <Container className="h-5 w-5 mr-2 text-purple-600" />
                Pods ({pods.length})
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => toggleSection('pods')}
              >
                {expandedSections.pods ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </Button>
            </div>
            <CardDescription>
              Pods gerenciados por este deployment
            </CardDescription>
          </CardHeader>
          {expandedSections.pods && (
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Nome
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Status
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Ready
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Restarts
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Motivo
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      IP
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Idade
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8">
                      Node
                    </TableHead>
                    <TableHead className="text-xs font-medium py-2 h-8 text-right">
                      Ações
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pods.map((pod: any, index: number) => {
                    const statusInfo = getPodStatus(pod);
                    const StatusIcon = statusInfo.icon;
                    const podReason = getPodReason(pod);

                    return (
                      <TableRow key={index}>
                        <TableCell className="font-medium py-2 w-48">
                          <div className="flex items-center space-x-2">
                            <StatusIcon
                              className={`h-4 w-4 ${statusInfo.color} flex-shrink-0`}
                            />
                            <span
                              className="cursor-pointer hover:text-blue-600 transition-colors hover:underline truncate min-w-0 flex-1"
                              onClick={() =>
                                navigate(
                                  `/cluster/pods/${pod.metadata?.name}/${namespaceName}`,
                                )
                              }
                              title={`${pod.metadata?.name} - Clique para ver detalhes do pod`}
                            >
                              {pod.metadata?.name}
                            </span>
                            {pod.metadata?.name && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 p-0 hover:bg-gray-100 flex-shrink-0"
                                onClick={() => {
                                  navigator.clipboard.writeText(
                                    pod.metadata.name,
                                  );
                                  showToast({
                                    title: 'Nome Copiado',
                                    description: `Nome "${pod.metadata.name}" copiado para a área de transferência`,
                                    variant: 'success',
                                  });
                                }}
                                title={`Copiar nome ${pod.metadata.name}`}
                              >
                                <Copy className="h-3 w-3" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="py-2">
                          {(() => {
                            const phase = pod.status?.phase;
                            const readyContainers =
                              pod.status?.containerStatuses?.filter(
                                (c: any) => c.ready,
                              ).length || 0;
                            const totalContainers =
                              pod.status?.containerStatuses?.length || 0;
                            const isReady =
                              readyContainers === totalContainers &&
                              totalContainers > 0;

                            if (phase === 'Running' && isReady) {
                              return (
                                <Badge className="bg-green-500 hover:bg-green-600">
                                  Ready
                                </Badge>
                              );
                            }
                            if (phase === 'Running' && !isReady) {
                              return (
                                <Badge className="bg-yellow-500 hover:bg-yellow-600">
                                  Starting
                                </Badge>
                              );
                            }
                            if (phase === 'Pending') {
                              return <Badge variant="secondary">Pending</Badge>;
                            }
                            if (phase === 'Failed') {
                              return (
                                <Badge variant="destructive">Failed</Badge>
                              );
                            }
                            return <Badge variant="secondary">{phase}</Badge>;
                          })()}
                        </TableCell>
                        <TableCell className="py-2">
                          {pod.status?.containerStatuses?.filter(
                            (c: any) => c.ready,
                          ).length || 0}
                          /{pod.status?.containerStatuses?.length || 0}
                        </TableCell>
                        <TableCell className="py-2">
                          {pod.status?.containerStatuses?.reduce(
                            (sum: number, c: any) =>
                              sum + (c.restartCount || 0),
                            0,
                          ) || 0}
                        </TableCell>
                        <TableCell className="text-sm py-2">
                          <div className="flex items-center space-x-2">
                            {(podReason.color === 'text-red-600' ||
                              podReason.color === 'text-yellow-600') && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 p-0 hover:bg-gray-100"
                                onClick={() =>
                                  handleErrorClick(
                                    pod.metadata?.name || '',
                                    podReason.text,
                                    podReason.title,
                                    podReason.containerName,
                                    podReason.isInitContainer,
                                  )
                                }
                                title="Ver detalhes do erro"
                              >
                                <AlertTriangle
                                  className={`h-3 w-3 ${podReason.color}`}
                                />
                              </Button>
                            )}
                            <span className={`${podReason.color} font-medium`}>
                              {podReason.text}
                            </span>
                          </div>
                        </TableCell>
                        <TableCell className="font-mono text-sm py-2">
                          <div className="flex items-center space-x-2">
                            <span>{pod.status?.podIP || 'N/A'}</span>
                            {pod.status?.podIP && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 p-0 hover:bg-gray-100"
                                onClick={() => {
                                  navigator.clipboard.writeText(
                                    pod.status.podIP,
                                  );
                                  showToast({
                                    title: 'IP Copiado',
                                    description: `IP ${pod.status.podIP} copiado para a área de transferência`,
                                    variant: 'success',
                                  });
                                }}
                                title={`Copiar IP ${pod.status.podIP}`}
                              >
                                <Copy className="h-3 w-3" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="py-2">
                          {getAge(pod.metadata?.creationTimestamp || '')}
                        </TableCell>
                        <TableCell className="py-2">
                          {pod.spec?.nodeName || 'N/A'}
                        </TableCell>
                        <TableCell className="text-right py-2">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>
                                Ações do Pod
                              </DropdownMenuLabel>
                              <DropdownMenuSeparator />

                              <DropdownMenuItem
                                onClick={() =>
                                  navigate(
                                    `/cluster/pods/${pod.metadata?.name}/${namespaceName}`,
                                  )
                                }
                              >
                                <Eye className="h-4 w-4 mr-2" />
                                Visualizar
                              </DropdownMenuItem>

                              <DropdownMenuSeparator />

                              <DropdownMenuItem disabled>
                                <Terminal className="h-4 w-4 mr-2" />
                                Console
                              </DropdownMenuItem>

                              <DropdownMenuItem
                                onClick={() => handlePodLogs(pod)}
                              >
                                <FileText className="h-4 w-4 mr-2" />
                                Logs
                              </DropdownMenuItem>

                              <DropdownMenuSeparator />

                              <DropdownMenuItem
                                onClick={() =>
                                  handleDeletePodClick(
                                    pod.metadata?.name,
                                    pod.metadata?.namespace,
                                  )
                                }
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Excluir
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
              {pods.length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  Nenhum pod encontrado
                </div>
              )}
            </CardContent>
          )}
        </Card>

        {/* ReplicaSets Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center">
                <Layers className="h-5 w-5 mr-2 text-blue-600" />
                ReplicaSets ({replicaSets.length})
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => toggleSection('replicaSets')}
              >
                {expandedSections.replicaSets ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </Button>
            </div>
            <CardDescription>
              ReplicaSets gerenciados por este deployment
            </CardDescription>
          </CardHeader>
          {expandedSections.replicaSets && (
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nome</TableHead>
                    <TableHead>Desired</TableHead>
                    <TableHead>Current</TableHead>
                    <TableHead>Ready</TableHead>
                    <TableHead>Ativo</TableHead>
                    <TableHead>Idade</TableHead>
                    <TableHead className="text-right">Ações</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {replicaSets
                    .sort(
                      (a, b) =>
                        (b.status?.replicas || 0) - (a.status?.replicas || 0),
                    )
                    .map((rs: any, index: number) => {
                      const isActive = (rs.spec?.replicas || 0) > 0;

                      return (
                        <TableRow key={index}>
                          <TableCell className="font-medium">
                            <div
                              className="cursor-pointer hover:text-blue-600 transition-colors hover:underline"
                              onClick={() => handleReplicaSetClick(rs)}
                              title="Clique para ver detalhes do ReplicaSet"
                            >
                              {rs.metadata?.name}
                            </div>
                          </TableCell>
                          <TableCell>{rs.spec?.replicas || 0}</TableCell>
                          <TableCell>{rs.status?.replicas || 0}</TableCell>
                          <TableCell>{rs.status?.readyReplicas || 0}</TableCell>
                          <TableCell>
                            <div className="flex items-center justify-center">
                              {isActive ? (
                                <CheckCircle
                                  className="h-4 w-4 text-green-600"
                                  title="ReplicaSet ativo"
                                />
                              ) : (
                                <div className="h-4 w-4" />
                              )}
                            </div>
                          </TableCell>
                          <TableCell>
                            {getAge(rs.metadata?.creationTimestamp || '')}
                          </TableCell>
                          <TableCell className="text-right">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="icon">
                                  <MoreVertical className="h-4 w-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                <DropdownMenuLabel>
                                  Ações do ReplicaSet
                                </DropdownMenuLabel>
                                <DropdownMenuSeparator />

                                <DropdownMenuItem
                                  onClick={() => handleReplicaSetClick(rs)}
                                >
                                  <Info className="h-4 w-4 mr-2" />
                                  Visualizar
                                </DropdownMenuItem>

                                <DropdownMenuSeparator />

                                <DropdownMenuItem
                                  onClick={() =>
                                    handleRestoreClick(
                                      rs.metadata?.name,
                                      rs.metadata?.namespace,
                                    )
                                  }
                                  disabled={restoring || isActive}
                                  className={
                                    isActive ? 'text-gray-400' : 'text-blue-600'
                                  }
                                >
                                  <RotateCcw className="h-4 w-4 mr-2" />
                                  {isActive ? 'Versão Atual' : 'Restaurar'}
                                </DropdownMenuItem>

                                <DropdownMenuSeparator />

                                <DropdownMenuItem
                                  onClick={() =>
                                    handleDeleteReplicaSetClick(rs)
                                  }
                                  disabled={deletingReplicaSet}
                                  className="text-red-600"
                                >
                                  <Trash2 className="h-4 w-4 mr-2" />
                                  Deletar
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                </TableBody>
              </Table>
              {replicaSets.length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  Nenhum ReplicaSet encontrado
                </div>
              )}
            </CardContent>
          )}
        </Card>

        {/* Events Section */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center">
                <Activity className="h-5 w-5 mr-2 text-green-600" />
                Eventos ({events.length})
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => toggleSection('events')}
              >
                {expandedSections.events ? (
                  <ChevronUp className="h-4 w-4" />
                ) : (
                  <ChevronDown className="h-4 w-4" />
                )}
              </Button>
            </div>
            <CardDescription>
              Eventos recentes relacionados ao deployment
            </CardDescription>
          </CardHeader>
          {expandedSections.events && (
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Tipo</TableHead>
                    <TableHead>Razão</TableHead>
                    <TableHead>Mensagem</TableHead>
                    <TableHead>Primeira Ocorrência</TableHead>
                    <TableHead>Última Ocorrência</TableHead>
                    <TableHead>Count</TableHead>
                    <TableHead className="text-right">Ações</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {events
                    .sort((a: any, b: any) => {
                      const aTime = new Date(
                        a.lastTimestamp || a.eventTime || 0,
                      ).getTime();
                      const bTime = new Date(
                        b.lastTimestamp || b.eventTime || 0,
                      ).getTime();
                      return bTime - aTime; // Mais recentes primeiro
                    })
                    .slice(0, 10)
                    .map((event: any, index: number) => (
                      <TableRow key={index}>
                        <TableCell>
                          <Badge
                            variant={
                              event.type === 'Warning'
                                ? 'destructive'
                                : 'default'
                            }
                          >
                            {event.type}
                          </Badge>
                        </TableCell>
                        <TableCell className="font-medium">
                          {event.reason}
                        </TableCell>
                        <TableCell
                          className="max-w-md truncate"
                          title={event.message}
                        >
                          {event.message}
                        </TableCell>
                        <TableCell className="text-sm">
                          {getAge(
                            event.firstTimestamp || event.eventTime || '',
                          )}
                        </TableCell>
                        <TableCell className="text-sm">
                          {getAge(event.lastTimestamp || event.eventTime || '')}
                        </TableCell>
                        <TableCell>{event.count || 1}</TableCell>
                        <TableCell className="text-right">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>
                                Ações do Evento
                              </DropdownMenuLabel>
                              <DropdownMenuSeparator />

                              <DropdownMenuItem
                                onClick={() => handleEventClick(event)}
                              >
                                <Info className="h-4 w-4 mr-2" />
                                Visualizar
                              </DropdownMenuItem>

                              <DropdownMenuItem
                                onClick={() => {
                                  navigator.clipboard.writeText(event.message);
                                  showToast({
                                    title: 'Mensagem Copiada',
                                    description:
                                      'Mensagem do evento copiada para área de transferência',
                                    variant: 'success',
                                  });
                                }}
                              >
                                <Copy className="h-4 w-4 mr-2" />
                                Copiar Mensagem
                              </DropdownMenuItem>

                              <DropdownMenuSeparator />

                              <DropdownMenuItem
                                onClick={() => handleDeleteEventClick(event)}
                                disabled={deletingEvent}
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Deletar
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                </TableBody>
              </Table>
              {events.length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  Nenhum evento encontrado
                </div>
              )}
            </CardContent>
          )}
        </Card>

        {/* Scale Modal */}
        <Dialog open={scaleModalOpen} onOpenChange={setScaleModalOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <ArrowUpDown className="h-5 w-5 mr-2" />
                Escalar Deployment
              </DialogTitle>
              <DialogDescription>
                Ajuste o número de réplicas do deployment{' '}
                <strong>"{deploymentName}"</strong>.
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid gap-2">
                <label htmlFor="replicas" className="text-sm font-medium">
                  Número de Réplicas
                </label>
                <div className="flex items-center space-x-2">
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={decrementReplicas}
                    disabled={newReplicas <= 0 || scaling}
                  >
                    <Minus className="h-4 w-4" />
                  </Button>
                  <div className="flex-1 text-center">
                    <input
                      id="replicas"
                      type="number"
                      min="0"
                      max="100"
                      value={newReplicas}
                      onChange={(e) => {
                        const value = Math.min(
                          Math.max(parseInt(e.target.value) || 0, 0),
                          100,
                        );
                        setNewReplicas(value);
                      }}
                      className="w-full text-center text-2xl font-bold border rounded-md py-2 px-3"
                      disabled={scaling}
                    />
                  </div>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={incrementReplicas}
                    disabled={newReplicas >= 100 || scaling}
                  >
                    <Plus className="h-4 w-4" />
                  </Button>
                </div>
                <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground">
                  <div>
                    <span className="font-medium">Atual:</span> {replicas}{' '}
                    réplica(s)
                  </div>
                  <div>
                    <span className="font-medium">Nova:</span> {newReplicas}{' '}
                    réplica(s)
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setScaleModalOpen(false);
                  setNewReplicas(1);
                }}
                disabled={scaling}
              >
                Cancelar
              </Button>
              <Button
                onClick={handleConfirmScale}
                disabled={scaling || newReplicas === replicas}
              >
                {scaling && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                {scaling ? 'Escalando...' : 'Aplicar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Pod Confirmation Modal */}
        <Dialog open={deletePodModalOpen} onOpenChange={setDeletePodModalOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="text-red-600">
                Confirmar Exclusão do Pod
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja deletar o pod{' '}
                <strong>"{podToDelete?.name}"</strong> do namespace{' '}
                <strong>"{podToDelete?.namespace}"</strong>?
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div className="flex items-start">
                  <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-yellow-800">
                    <p className="font-medium mb-1">⚠️ Atenção:</p>
                    <p>Esta ação irá:</p>
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Deletar o pod imediatamente</li>
                      <li>
                        O deployment pode recriar um novo pod automaticamente
                      </li>
                      <li>Possível interrupção temporária do serviço</li>
                      <li>Logs e dados não persistidos serão perdidos</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setDeletePodModalOpen(false);
                  setPodToDelete(null);
                }}
                disabled={deletingPod}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeletePod}
                disabled={deletingPod}
              >
                {deletingPod && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingPod ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Restore ReplicaSet Confirmation Modal */}
        <Dialog open={restoreModalOpen} onOpenChange={setRestoreModalOpen}>
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="text-blue-600">
                Confirmar Restauração
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja restaurar o deployment{' '}
                <strong>"{deploymentName}"</strong> para o ReplicaSet{' '}
                <strong>"{replicaSetToRestore?.name}"</strong>?
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-start">
                  <Info className="h-5 w-5 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-blue-800">
                    <p className="font-medium mb-1">ℹ️ O que vai acontecer:</p>
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>
                        O deployment será revertido para a versão anterior
                      </li>
                      <li>Pods atuais serão substituídos gradualmente</li>
                      <li>Rolling update será executado automaticamente</li>
                      <li>O processo pode levar alguns minutos</li>
                      <li>Você pode reverter novamente se necessário</li>
                    </ul>
                  </div>
                </div>
              </div>
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mt-3">
                <div className="flex items-start">
                  <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-yellow-800">
                    <p className="font-medium mb-1">⚠️ Importante:</p>
                    <p>
                      Esta ação irá alterar a versão ativa do seu deployment.
                      Certifique-se de que a versão anterior é estável e
                      compatível.
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setRestoreModalOpen(false);
                  setReplicaSetToRestore(null);
                }}
                disabled={restoring}
              >
                Cancelar
              </Button>
              <Button
                onClick={handleConfirmRestore}
                disabled={restoring}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {restoring && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                {restoring ? 'Restaurando...' : 'Sim, Restaurar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Error Details Modal */}
        <Dialog open={errorModalOpen} onOpenChange={setErrorModalOpen}>
          <DialogContent className="sm:max-w-2xl">
            <DialogHeader>
              <DialogTitle className="text-red-600 flex items-center">
                <AlertTriangle className="h-5 w-5 mr-2" />
                Detalhes do Erro
              </DialogTitle>
              <DialogDescription>
                Informações detalhadas sobre o erro no pod{' '}
                <strong>"{selectedError?.podName}"</strong>
                {selectedError?.containerName && (
                  <>
                    {' - Container: '}
                    <strong>"{selectedError.containerName}"</strong>
                    {selectedError.isInitContainer && (
                      <Badge variant="outline" className="ml-2 text-xs">
                        Init Container
                      </Badge>
                    )}
                  </>
                )}
              </DialogDescription>
            </DialogHeader>
            <div className="py-4 space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-700">
                  Tipo do Erro:
                </label>
                <div className="mt-1 p-2 bg-red-50 border border-red-200 rounded-md">
                  <Badge variant="destructive" className="text-sm">
                    {selectedError?.reason}
                  </Badge>
                </div>
              </div>

              <div>
                <label className="text-sm font-medium text-gray-700">
                  Mensagem Completa:
                </label>
                <div className="mt-1 p-3 bg-gray-50 border border-gray-200 rounded-md max-h-64 overflow-y-auto">
                  <pre className="text-xs font-mono whitespace-pre-wrap break-words leading-relaxed">
                    {selectedError?.error}
                  </pre>
                </div>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-start">
                  <Info className="h-5 w-5 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-blue-800">
                    <p className="font-medium mb-1">💡 Dicas para resolver:</p>
                    <ul className="list-disc list-inside space-y-1">
                      {selectedError?.reason.includes('Image') && (
                        <>
                          <li>Verifique se a imagem existe no registry</li>
                          <li>Confirme se as credenciais estão corretas</li>
                          <li>Verifique se a tag da imagem está correta</li>
                          <li>Teste o pull da imagem manualmente</li>
                        </>
                      )}
                      {selectedError?.reason.includes('Config') && (
                        <>
                          <li>Verifique se os ConfigMaps existem</li>
                          <li>Confirme se os Secrets estão corretos</li>
                          <li>Verifique as variáveis de ambiente</li>
                        </>
                      )}
                      {selectedError?.reason.includes('Crash') && (
                        <>
                          <li>Verifique os logs do container</li>
                          <li>
                            Confirme se a aplicação está configurada
                            corretamente
                          </li>
                          <li>Verifique dependências e recursos</li>
                        </>
                      )}
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  navigator.clipboard.writeText(selectedError?.error || '');
                  showToast({
                    title: 'Erro Copiado',
                    description:
                      'A mensagem de erro foi copiada para a área de transferência',
                    variant: 'success',
                  });
                }}
              >
                <Copy className="h-4 w-4 mr-2" />
                Copiar Erro
              </Button>
              {selectedError?.containerName && (
                <Button
                  variant="outline"
                  onClick={() => {
                    setErrorModalOpen(false);
                    handlePodLogs(
                      {
                        metadata: { name: selectedError.podName },
                      },
                      selectedError.containerName,
                    );
                  }}
                >
                  <FileText className="h-4 w-4 mr-2" />
                  Ver Logs do Container
                </Button>
              )}
              <Button
                onClick={() => {
                  setErrorModalOpen(false);
                  setSelectedError(null);
                }}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* ReplicaSet Details Modal */}
        <Dialog
          open={replicaSetModalOpen}
          onOpenChange={setReplicaSetModalOpen}
        >
          <DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <Layers className="h-5 w-5 mr-2 text-blue-600" />
                Detalhes do ReplicaSet
              </DialogTitle>
              <DialogDescription>
                Informações específicas do ReplicaSet{' '}
                {selectedReplicaSet?.metadata?.name}
              </DialogDescription>
            </DialogHeader>

            {loadingReplicaSetDetails ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-8 w-8 animate-spin" />
                <span className="ml-2">Carregando detalhes...</span>
              </div>
            ) : selectedReplicaSet ? (
              <div className="space-y-6">
                {/* Informações Específicas */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Info className="h-4 w-4 mr-2" />
                    Informações da Versão
                  </h3>
                  <div className="grid grid-cols-1 gap-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                        <span className="font-medium text-blue-800">
                          Revision:
                        </span>
                        <p className="text-sm text-blue-700">
                          #
                          {selectedReplicaSet.metadata?.annotations?.[
                            'deployment.kubernetes.io/revision'
                          ] || 'N/A'}
                        </p>
                      </div>
                      <div className="p-3 bg-purple-50 rounded-lg border border-purple-200">
                        <span className="font-medium text-purple-800">
                          Pod Template Hash:
                        </span>
                        <p className="text-sm text-purple-700 font-mono break-all">
                          {selectedReplicaSet.metadata?.labels?.[
                            'pod-template-hash'
                          ] || 'N/A'}
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Status:</span>
                        <p className="text-sm text-gray-600">
                          {(selectedReplicaSet.spec?.replicas || 0) > 0 ? (
                            <Badge className="bg-green-500">Ativo</Badge>
                          ) : (
                            <Badge variant="secondary">Inativo</Badge>
                          )}
                        </p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Controlado por:</span>
                        <p className="text-sm text-gray-600">
                          {selectedReplicaSet.metadata?.ownerReferences?.[0]
                            ?.name || 'N/A'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Container Info - só se diferente do atual */}
                {selectedReplicaSet.spec?.template?.spec?.containers && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Container className="h-4 w-4 mr-2" />
                      Containers desta Versão
                    </h3>
                    <div className="space-y-2">
                      {selectedReplicaSet.spec.template.spec.containers.map(
                        (container: any, index: number) => (
                          <div
                            key={index}
                            className="p-3 bg-gray-50 rounded-lg border"
                          >
                            <div className="flex items-center justify-between mb-2">
                              <span className="font-medium">
                                {container.name}
                              </span>
                              <Copy
                                className="h-4 w-4 cursor-pointer hover:text-blue-600"
                                onClick={() => {
                                  navigator.clipboard.writeText(
                                    container.image,
                                  );
                                  showToast({
                                    title: 'Imagem Copiada',
                                    description:
                                      'Nome da imagem copiado para área de transferência',
                                    variant: 'success',
                                  });
                                }}
                                title="Copiar imagem"
                              />
                            </div>
                            <div className="text-sm text-gray-600 font-mono break-all">
                              {container.image}
                            </div>
                            {container.ports && (
                              <div className="flex items-center mt-2 space-x-2">
                                {container.ports.map(
                                  (port: any, portIndex: number) => (
                                    <Badge
                                      key={portIndex}
                                      variant="outline"
                                      className="text-xs"
                                    >
                                      {port.containerPort}/
                                      {port.protocol || 'TCP'}
                                    </Badge>
                                  ),
                                )}
                              </div>
                            )}
                          </div>
                        ),
                      )}
                    </div>
                  </div>
                )}

                {/* Pods deste ReplicaSet */}
                {replicaSetPods.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Activity className="h-4 w-4 mr-2" />
                      Pods desta Versão ({replicaSetPods.length})
                    </h3>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {replicaSetPods.map((pod: any, index: number) => {
                        const statusInfo = getPodStatus(pod);
                        const StatusIcon = statusInfo.icon;

                        return (
                          <div
                            key={index}
                            className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border"
                          >
                            <div className="flex items-center space-x-2">
                              <StatusIcon
                                className={`h-4 w-4 ${statusInfo.color}`}
                              />
                              <span className="font-medium">
                                {pod.metadata?.name}
                              </span>
                            </div>
                            <div className="flex items-center space-x-2">
                              <Badge variant="outline" className="text-xs">
                                {pod.status?.phase || 'Unknown'}
                              </Badge>
                              <span className="text-sm text-gray-500">
                                {getAge(pod.metadata?.creationTimestamp || '')}
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* Eventos específicos */}
                {replicaSetEvents.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <AlertCircle className="h-4 w-4 mr-2" />
                      Eventos Específicos ({replicaSetEvents.length})
                    </h3>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {replicaSetEvents
                        .sort((a: any, b: any) => {
                          const aTime = new Date(
                            a.lastTimestamp || a.eventTime || 0,
                          ).getTime();
                          const bTime = new Date(
                            b.lastTimestamp || b.eventTime || 0,
                          ).getTime();
                          return bTime - aTime; // Mais recentes primeiro
                        })
                        .slice(0, 5)
                        .map((event: any, index: number) => (
                          <div
                            key={index}
                            className="p-3 bg-gray-50 rounded-lg border"
                          >
                            <div className="flex items-center justify-between mb-1">
                              <Badge
                                variant={
                                  event.type === 'Warning'
                                    ? 'destructive'
                                    : 'default'
                                }
                                className="text-xs"
                              >
                                {event.type}
                              </Badge>
                              <span className="text-xs text-gray-500">
                                {getAge(
                                  event.lastTimestamp || event.eventTime || '',
                                )}
                              </span>
                            </div>
                            <div className="text-sm font-medium">
                              {event.reason}
                            </div>
                            <div className="text-xs text-gray-600 mt-1">
                              {event.message}
                            </div>
                          </div>
                        ))}
                    </div>
                  </div>
                )}

                {/* Labels específicos */}
                {selectedReplicaSet.metadata?.labels &&
                  Object.keys(selectedReplicaSet.metadata.labels).length >
                    0 && (
                    <div className="space-y-4">
                      <h3 className="text-lg font-semibold flex items-center">
                        <Tag className="h-4 w-4 mr-2" />
                        Labels da Versão
                      </h3>
                      <div className="flex flex-wrap gap-1">
                        {Object.entries(selectedReplicaSet.metadata.labels).map(
                          ([key, value]) => (
                            <Badge
                              key={key}
                              variant="secondary"
                              className="text-xs"
                            >
                              {key}: {value as string}
                            </Badge>
                          ),
                        )}
                      </div>
                    </div>
                  )}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum detalhe disponível
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setReplicaSetModalOpen(false);
                  setSelectedReplicaSet(null);
                  setReplicaSetEvents([]);
                  setReplicaSetPods([]);
                }}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Event Details Modal */}
        <Dialog open={eventModalOpen} onOpenChange={setEventModalOpen}>
          <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <Activity className="h-5 w-5 mr-2 text-green-600" />
                Detalhes do Evento
              </DialogTitle>
              <DialogDescription>
                Informações completas sobre o evento do Kubernetes
              </DialogDescription>
            </DialogHeader>

            {selectedEvent ? (
              <div className="space-y-6">
                {/* Informações Básicas */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Info className="h-4 w-4 mr-2" />
                    Informações Básicas
                  </h3>
                  <div className="grid grid-cols-1 gap-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Tipo:</span>
                        <div className="mt-1">
                          <Badge
                            variant={
                              selectedEvent.type === 'Warning'
                                ? 'destructive'
                                : 'default'
                            }
                          >
                            {selectedEvent.type}
                          </Badge>
                        </div>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Razão:</span>
                        <p className="text-sm text-gray-600 mt-1 font-medium">
                          {selectedEvent.reason}
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Count:</span>
                        <p className="text-sm text-gray-600 mt-1">
                          {selectedEvent.count || 1} ocorrência(s)
                        </p>
                      </div>
                      <div className="p-3 bg-gray-50 rounded-lg">
                        <span className="font-medium">Reportado por:</span>
                        <p className="text-sm text-gray-600 mt-1">
                          {selectedEvent.reportingComponent ||
                            selectedEvent.source?.component ||
                            'N/A'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Objeto Envolvido */}
                {selectedEvent.involvedObject && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Container className="h-4 w-4 mr-2" />
                      Objeto Envolvido
                    </h3>
                    <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                      <div className="grid grid-cols-2 gap-3 text-sm">
                        <div>
                          <span className="font-medium text-blue-800">
                            Tipo:
                          </span>
                          <p className="text-blue-700">
                            {selectedEvent.involvedObject.kind}
                          </p>
                        </div>
                        <div>
                          <span className="font-medium text-blue-800">
                            Nome:
                          </span>
                          <p className="text-blue-700">
                            {selectedEvent.involvedObject.name}
                          </p>
                        </div>
                        {selectedEvent.involvedObject.namespace && (
                          <>
                            <div>
                              <span className="font-medium text-blue-800">
                                Namespace:
                              </span>
                              <p className="text-blue-700">
                                {selectedEvent.involvedObject.namespace}
                              </p>
                            </div>
                            <div>
                              <span className="font-medium text-blue-800">
                                UID:
                              </span>
                              <p className="text-blue-700 font-mono text-xs">
                                {selectedEvent.involvedObject.uid}
                              </p>
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                )}

                {/* Mensagem Completa */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <FileText className="h-4 w-4 mr-2" />
                    Mensagem Completa
                  </h3>
                  <div className="p-4 bg-gray-50 rounded-lg border">
                    <div className="flex items-start justify-between mb-2">
                      <span className="text-sm font-medium text-gray-700">
                        Descrição:
                      </span>
                      <Copy
                        className="h-4 w-4 cursor-pointer hover:text-blue-600"
                        onClick={() => {
                          navigator.clipboard.writeText(selectedEvent.message);
                          showToast({
                            title: 'Mensagem Copiada',
                            description:
                              'Mensagem copiada para área de transferência',
                            variant: 'success',
                          });
                        }}
                        title="Copiar mensagem"
                      />
                    </div>
                    <div className="text-sm text-gray-600 whitespace-pre-wrap break-words leading-relaxed">
                      {selectedEvent.message}
                    </div>
                  </div>
                </div>

                {/* Timestamps */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Clock className="h-4 w-4 mr-2" />
                    Timestamps
                  </h3>
                  <div className="grid grid-cols-1 gap-3">
                    {selectedEvent.firstTimestamp && (
                      <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                        <span className="font-medium text-green-800">
                          Primeira Ocorrência:
                        </span>
                        <div className="text-sm text-green-700 mt-1">
                          <div>
                            {new Date(
                              selectedEvent.firstTimestamp,
                            ).toLocaleString('pt-BR')}
                          </div>
                          <div className="text-xs">
                            ({getAge(selectedEvent.firstTimestamp)} atrás)
                          </div>
                        </div>
                      </div>
                    )}

                    {selectedEvent.lastTimestamp && (
                      <div className="p-3 bg-orange-50 rounded-lg border border-orange-200">
                        <span className="font-medium text-orange-800">
                          Última Ocorrência:
                        </span>
                        <div className="text-sm text-orange-700 mt-1">
                          <div>
                            {new Date(
                              selectedEvent.lastTimestamp,
                            ).toLocaleString('pt-BR')}
                          </div>
                          <div className="text-xs">
                            ({getAge(selectedEvent.lastTimestamp)} atrás)
                          </div>
                        </div>
                      </div>
                    )}

                    {selectedEvent.eventTime && (
                      <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                        <span className="font-medium text-blue-800">
                          Event Time:
                        </span>
                        <div className="text-sm text-blue-700 mt-1">
                          <div>
                            {new Date(selectedEvent.eventTime).toLocaleString(
                              'pt-BR',
                            )}
                          </div>
                          <div className="text-xs">
                            ({getAge(selectedEvent.eventTime)} atrás)
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Metadados Técnicos */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Database className="h-4 w-4 mr-2" />
                    Metadados Técnicos
                  </h3>
                  <div className="space-y-2">
                    {selectedEvent.metadata?.name && (
                      <div className="flex justify-between p-2 bg-gray-50 rounded text-sm">
                        <span className="font-medium">Nome do Evento:</span>
                        <span className="font-mono">
                          {selectedEvent.metadata.name}
                        </span>
                      </div>
                    )}

                    {selectedEvent.metadata?.namespace && (
                      <div className="flex justify-between p-2 bg-gray-50 rounded text-sm">
                        <span className="font-medium">Namespace:</span>
                        <span>{selectedEvent.metadata.namespace}</span>
                      </div>
                    )}

                    {selectedEvent.action && (
                      <div className="flex justify-between p-2 bg-gray-50 rounded text-sm">
                        <span className="font-medium">Ação:</span>
                        <span>{selectedEvent.action}</span>
                      </div>
                    )}

                    {selectedEvent.reportingInstance && (
                      <div className="flex justify-between p-2 bg-gray-50 rounded text-sm">
                        <span className="font-medium">Instância:</span>
                        <span className="font-mono">
                          {selectedEvent.reportingInstance}
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                {/* Dicas de Troubleshooting */}
                {selectedEvent.type === 'Warning' && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <AlertTriangle className="h-4 w-4 mr-2" />
                      Sugestões de Troubleshooting
                    </h3>
                    <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                      <div className="text-sm text-yellow-800">
                        <p className="font-medium mb-2">
                          💡 Dicas para investigar este evento:
                        </p>
                        <ul className="list-disc list-inside space-y-1">
                          {selectedEvent.reason.includes('Failed') && (
                            <li>
                              Verifique os logs do pod ou container envolvido
                            </li>
                          )}
                          {selectedEvent.reason.includes('Image') && (
                            <>
                              <li>Confirme se a imagem existe no registry</li>
                              <li>
                                Verifique as credenciais de acesso ao registry
                              </li>
                            </>
                          )}
                          {selectedEvent.reason.includes('Mount') && (
                            <li>
                              Verifique se os volumes e PVCs estão disponíveis
                            </li>
                          )}
                          {selectedEvent.reason.includes('Schedule') && (
                            <li>Verifique recursos disponíveis nos nodes</li>
                          )}
                          <li>
                            Execute:{' '}
                            <code className="bg-gray-200 px-1 rounded">
                              kubectl describe{' '}
                              {selectedEvent.involvedObject?.kind?.toLowerCase()}{' '}
                              {selectedEvent.involvedObject?.name}
                            </code>
                          </li>
                          <li>
                            Verifique eventos relacionados:{' '}
                            <code className="bg-gray-200 px-1 rounded">
                              kubectl get events --sort-by='.lastTimestamp'
                            </code>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum detalhe disponível
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setEventModalOpen(false);
                  setSelectedEvent(null);
                }}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Event Confirmation Modal */}
        <Dialog
          open={deleteEventModalOpen}
          onOpenChange={setDeleteEventModalOpen}
        >
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="text-red-600">
                Confirmar Exclusão do Evento
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja deletar o evento{' '}
                <strong>"{eventToDelete?.reason}"</strong>?
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div className="flex items-start">
                  <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-yellow-800">
                    <p className="font-medium mb-1">⚠️ Atenção:</p>
                    <p>Esta ação irá:</p>
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Deletar permanentemente este evento</li>
                      <li>Remover o histórico de troubleshooting</li>
                      <li>Esta ação não pode ser desfeita</li>
                      <li>O objeto relacionado não será afetado</li>
                    </ul>
                  </div>
                </div>
              </div>

              {eventToDelete && (
                <div className="mt-4 p-3 bg-gray-50 rounded-lg border">
                  <h4 className="font-medium text-sm mb-2">
                    Detalhes do evento:
                  </h4>
                  <div className="space-y-1 text-sm text-gray-600">
                    <div>
                      <strong>Tipo:</strong> {eventToDelete.type}
                    </div>
                    <div>
                      <strong>Razão:</strong> {eventToDelete.reason}
                    </div>
                    <div>
                      <strong>Objeto:</strong>{' '}
                      {eventToDelete.involvedObject?.kind}/
                      {eventToDelete.involvedObject?.name}
                    </div>
                    <div>
                      <strong>Mensagem:</strong>{' '}
                      {eventToDelete.message?.substring(0, 100)}
                      {eventToDelete.message?.length > 100 ? '...' : ''}
                    </div>
                  </div>
                </div>
              )}
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setDeleteEventModalOpen(false);
                  setEventToDelete(null);
                }}
                disabled={deletingEvent}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteEvent}
                disabled={deletingEvent}
              >
                {deletingEvent && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingEvent ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete ReplicaSet Confirmation Modal */}
        <Dialog
          open={deleteReplicaSetModalOpen}
          onOpenChange={setDeleteReplicaSetModalOpen}
        >
          <DialogContent className="sm:max-w-[425px]">
            <DialogHeader>
              <DialogTitle className="text-red-600">
                Confirmar Exclusão do ReplicaSet
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja deletar o ReplicaSet{' '}
                <strong>"{replicaSetToDelete?.metadata?.name}"</strong>?
              </DialogDescription>
            </DialogHeader>
            <div className="py-4">
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div className="flex items-start">
                  <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-yellow-800">
                    <p className="font-medium mb-1">⚠️ Atenção:</p>
                    <p>Esta ação irá:</p>
                    <ul className="list-disc list-inside mt-2 space-y-1">
                      <li>Deletar permanentemente este ReplicaSet</li>
                      <li>Terminar todos os pods associados</li>
                      <li>Remover o histórico de versão</li>
                      <li>Esta ação não pode ser desfeita</li>
                      <li>O deployment principal não será afetado</li>
                    </ul>
                  </div>
                </div>
              </div>

              {replicaSetToDelete && (
                <div className="mt-4 p-3 bg-gray-50 rounded-lg border">
                  <h4 className="font-medium text-sm mb-2">
                    Detalhes do ReplicaSet:
                  </h4>
                  <div className="space-y-1 text-sm text-gray-600">
                    <div>
                      <strong>Nome:</strong> {replicaSetToDelete.metadata?.name}
                    </div>
                    <div>
                      <strong>Namespace:</strong>{' '}
                      {replicaSetToDelete.metadata?.namespace}
                    </div>
                    <div>
                      <strong>Replicas Desejadas:</strong>{' '}
                      {replicaSetToDelete.spec?.replicas || 0}
                    </div>
                    <div>
                      <strong>Replicas Atuais:</strong>{' '}
                      {replicaSetToDelete.status?.replicas || 0}
                    </div>
                    <div>
                      <strong>Replicas Prontas:</strong>{' '}
                      {replicaSetToDelete.status?.readyReplicas || 0}
                    </div>
                    <div>
                      <strong>Idade:</strong>{' '}
                      {getAge(
                        replicaSetToDelete.metadata?.creationTimestamp || '',
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => {
                  setDeleteReplicaSetModalOpen(false);
                  setReplicaSetToDelete(null);
                }}
                disabled={deletingReplicaSet}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteReplicaSet}
                disabled={deletingReplicaSet}
              >
                {deletingReplicaSet && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingReplicaSet ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Deployment Confirmation Modal */}
        <Dialog
          open={deleteDeploymentModalOpen}
          onOpenChange={setDeleteDeploymentModalOpen}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle className="flex items-center text-red-600">
                <Trash className="h-5 w-5 mr-2" />
                Excluir Deployment
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja excluir o deployment{' '}
                <strong>"{deploymentName}"</strong> do namespace{' '}
                <strong>"{namespaceName}"</strong>?
                <br />
                <br />
                <div className="bg-red-50 p-3 rounded-lg border border-red-200">
                  <p className="text-red-800 font-medium text-sm">
                    ⚠️ Esta ação é irreversível!
                  </p>
                  <ul className="text-red-700 text-sm mt-2 space-y-1">
                    <li>• Todos os pods serão terminados</li>
                    <li>• O deployment será removido permanentemente</li>
                    <li>• Os dados não poderão ser recuperados</li>
                  </ul>
                </div>
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteDeploymentModalOpen(false)}
                disabled={deletingDeployment}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteDeployment}
                disabled={deletingDeployment}
              >
                {deletingDeployment && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingDeployment
                  ? 'Excluindo...'
                  : 'Sim, Excluir Deployment'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Service Confirmation Modal */}
        <Dialog
          open={deleteServiceModalOpen}
          onOpenChange={setDeleteServiceModalOpen}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle className="flex items-center text-red-600">
                <Trash className="h-5 w-5 mr-2" />
                Excluir Service
              </DialogTitle>
              <DialogDescription>
                Tem certeza que deseja excluir o service{' '}
                <strong>{serviceToDelete?.metadata?.name}</strong>?
                <br />
                <br />
                Esta ação não pode ser desfeita. O service será removido
                permanentemente do namespace <strong>{namespaceName}</strong>.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeleteServiceModalOpen(false)}
                disabled={deletingService}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleConfirmDeleteService}
                disabled={deletingService}
              >
                {deletingService && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {deletingService ? 'Excluindo...' : 'Sim, Excluir Service'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* YAML Editors - Todos no mesmo nível */}
        <YamlEditor
          open={yamlDrawerOpen}
          onOpenChange={setYamlDrawerOpen}
          resourceType="deployment"
          resourceName={deploymentName || ''}
          namespace={namespaceName || ''}
          title={`YAML do Deployment - ${deploymentName}`}
          onSave={() => {
            setTimeout(() => {
              backgroundRefetch();
            }, 1000);
          }}
        />

        <YamlEditor
          open={serviceYamlModalOpen}
          onOpenChange={setServiceYamlModalOpen}
          resourceType="service"
          resourceName={selectedServiceName}
          namespace={namespaceName || ''}
          title={`Service YAML - ${selectedServiceName}`}
          onSave={() => {
            setTimeout(() => {
              backgroundRefetch();
            }, 1000);
          }}
        />

        <YamlEditor
          open={secretYamlModalOpen}
          onOpenChange={setSecretYamlModalOpen}
          resourceType="secret"
          resourceName={selectedSecretName}
          namespace={namespaceName || ''}
          title={`Secret YAML - ${selectedSecretName}`}
          onSave={() => {
            setTimeout(() => {
              backgroundRefetch();
            }, 1000);
          }}
        />

        <YamlEditor
          open={configMapYamlModalOpen}
          onOpenChange={setConfigMapYamlModalOpen}
          resourceType="configmap"
          resourceName={selectedConfigMapName}
          namespace={namespaceName || ''}
          title={`ConfigMap YAML - ${selectedConfigMapName}`}
          onSave={() => {
            setTimeout(() => {
              backgroundRefetch();
            }, 1000);
          }}
        />

        {/* Logs Modal */}
        <LogsModal
          open={logsModalOpen}
          onOpenChange={setLogsModalOpen}
          podName={selectedPodForLogs?.metadata?.name || ''}
          namespace={namespaceName || ''}
          title="Logs do Pod"
        />

        {/* Modal para visualizar chaves e valores do Secret */}
        <Dialog
          open={secretKeysModalOpen}
          onOpenChange={setSecretKeysModalOpen}
        >
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <Shield className="h-5 w-5 mr-2 text-orange-600" />
                Chaves do Secret: {selectedSecretData?.metadata?.name}
              </DialogTitle>
              <DialogDescription>
                Visualização das chaves e valores do Secret (valores são
                mostrados decodificados)
              </DialogDescription>
            </DialogHeader>

            {selectedSecretData ? (
              <div className="max-h-[400px] overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[200px]">Chave</TableHead>
                      <TableHead>Valor</TableHead>
                      <TableHead className="w-[100px]">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {Object.entries(selectedSecretData.data || {}).map(
                      ([key, encodedValue]) => {
                        // Decodificar valor base64
                        let decodedValue = '';
                        try {
                          decodedValue = atob(encodedValue as string);
                        } catch (e) {
                          decodedValue = '(Erro ao decodificar)';
                        }

                        return (
                          <TableRow key={key}>
                            <TableCell className="font-medium">{key}</TableCell>
                            <TableCell>
                              <div className="max-w-[300px] truncate font-mono text-sm bg-gray-50 p-2 rounded">
                                {decodedValue.length > 100
                                  ? `${decodedValue.substring(0, 100)}...`
                                  : decodedValue}
                              </div>
                            </TableCell>
                            <TableCell>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => {
                                  navigator.clipboard.writeText(decodedValue);
                                  showToast({
                                    title: 'Valor Copiado',
                                    description: `Valor da chave "${key}" copiado para a área de transferência`,
                                    variant: 'success',
                                  });
                                }}
                              >
                                <Copy className="h-4 w-4" />
                              </Button>
                            </TableCell>
                          </TableRow>
                        );
                      },
                    )}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum dado disponível
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setSecretKeysModalOpen(false)}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Modal para visualizar chaves e valores do ConfigMap */}
        <Dialog
          open={configMapKeysModalOpen}
          onOpenChange={setConfigMapKeysModalOpen}
        >
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <Database className="h-5 w-5 mr-2 text-blue-600" />
                Chaves do ConfigMap: {selectedConfigMapData?.metadata?.name}
              </DialogTitle>
              <DialogDescription>
                Visualização das chaves e valores do ConfigMap
              </DialogDescription>
            </DialogHeader>

            {selectedConfigMapData ? (
              <div className="max-h-[400px] overflow-y-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[200px]">Chave</TableHead>
                      <TableHead>Valor</TableHead>
                      <TableHead className="w-[100px]">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {Object.entries(selectedConfigMapData.data || {}).map(
                      ([key, value]) => (
                        <TableRow key={key}>
                          <TableCell className="font-medium">{key}</TableCell>
                          <TableCell>
                            <div className="max-w-[300px] truncate font-mono text-sm bg-gray-50 p-2 rounded">
                              {typeof value === 'string' && value.length > 100
                                ? `${value.substring(0, 100)}...`
                                : String(value)}
                            </div>
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                navigator.clipboard.writeText(String(value));
                                showToast({
                                  title: 'Valor Copiado',
                                  description: `Valor da chave "${key}" copiado para a área de transferência`,
                                  variant: 'success',
                                });
                              }}
                            >
                              <Copy className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ),
                    )}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum dado disponível
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setConfigMapKeysModalOpen(false)}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Modal para visualizar credenciais do Docker Registry */}
        <Dialog
          open={dockerConfigModalOpen}
          onOpenChange={setDockerConfigModalOpen}
        >
          <DialogContent className="sm:max-w-[700px]">
            <DialogHeader>
              <DialogTitle className="flex items-center">
                <Container className="h-5 w-5 mr-2 text-purple-600" />
                Credenciais Docker Registry:{' '}
                {selectedDockerConfigData?.metadata?.name}
              </DialogTitle>
              <DialogDescription>
                Visualização estruturada das credenciais de acesso ao registry
                Docker
              </DialogDescription>
            </DialogHeader>

            {selectedDockerConfigData ? (
              <div className="max-h-[500px] overflow-y-auto space-y-4">
                {(() => {
                  try {
                    // Decodificar o .dockerconfigjson
                    const dockerconfigjsonEncoded =
                      selectedDockerConfigData.data?.['.dockerconfigjson'];
                    if (!dockerconfigjsonEncoded) {
                      return (
                        <div className="text-center py-8 text-muted-foreground">
                          Dados do Docker config não encontrados
                        </div>
                      );
                    }

                    const dockerConfigRaw = atob(dockerconfigjsonEncoded);
                    const dockerConfig = JSON.parse(dockerConfigRaw);
                    const auths = dockerConfig.auths || {};

                    return Object.entries(auths).map(
                      ([registry, config]: [string, any]) => {
                        let username = '';
                        let password = '';
                        let email = '';

                        // Tentar decodificar auth se existir
                        if (config.auth) {
                          try {
                            const authDecoded = atob(config.auth);
                            const [user, pass] = authDecoded.split(':');
                            username = user || '';
                            password = pass || '';
                          } catch (e) {
                            // Ignore decode error
                          }
                        }

                        // Usar username/password diretos se disponíveis
                        if (config.username) username = config.username;
                        if (config.password) password = config.password;
                        if (config.email) email = config.email;

                        // Detectar tipo de registry
                        const isDockerHub =
                          registry.includes('docker.io') ||
                          registry === 'https://index.docker.io/v1/';
                        const isQuay = registry.includes('quay.io');
                        const isGCR = registry.includes('gcr.io');
                        const isECR = registry.includes('amazonaws.com');
                        const isCustom =
                          !isDockerHub && !isQuay && !isGCR && !isECR;

                        let registryType = 'Custom Registry';
                        let badgeColor = 'bg-purple-100 text-purple-700';

                        if (isDockerHub) {
                          registryType = 'Docker Hub';
                          badgeColor = 'bg-blue-100 text-blue-700';
                        } else if (isQuay) {
                          registryType = 'Quay.io';
                          badgeColor = 'bg-red-100 text-red-700';
                        } else if (isGCR) {
                          registryType = 'Google Container Registry';
                          badgeColor = 'bg-green-100 text-green-700';
                        } else if (isECR) {
                          registryType = 'AWS ECR';
                          badgeColor = 'bg-orange-100 text-orange-700';
                        }

                        return (
                          <div
                            key={registry}
                            className="border rounded-lg p-4 bg-purple-50"
                          >
                            <div className="flex items-center justify-between mb-3">
                              <div>
                                <h4 className="font-medium text-purple-800">
                                  Registry: {registry}
                                </h4>
                                <p className="text-sm text-purple-600 mt-1">
                                  {registryType}
                                </p>
                              </div>
                              <Badge variant="outline" className={badgeColor}>
                                {registryType}
                              </Badge>
                            </div>

                            <div className="grid grid-cols-1 gap-3">
                              {/* Para Docker Hub e Quay.io - só Username e Password */}
                              {isDockerHub || isQuay ? (
                                <div className="grid grid-cols-2 gap-4">
                                  <div className="bg-white p-3 rounded border">
                                    <div className="flex items-center justify-between">
                                      <span className="text-sm font-medium text-gray-600">
                                        Username:
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => {
                                          navigator.clipboard.writeText(
                                            username,
                                          );
                                          showToast({
                                            title: 'Username Copiado',
                                            description:
                                              'Username copiado para a área de transferência',
                                            variant: 'success',
                                          });
                                        }}
                                      >
                                        <Copy className="h-3 w-3" />
                                      </Button>
                                    </div>
                                    <div
                                      className="font-mono text-sm mt-1 truncate"
                                      title={username}
                                    >
                                      {username || '(Não especificado)'}
                                    </div>
                                  </div>

                                  <div className="bg-white p-3 rounded border">
                                    <div className="flex items-center justify-between">
                                      <span className="text-sm font-medium text-gray-600">
                                        Password:
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => {
                                          navigator.clipboard.writeText(
                                            password,
                                          );
                                          showToast({
                                            title: 'Password Copiado',
                                            description:
                                              'Password copiado para a área de transferência',
                                            variant: 'success',
                                          });
                                        }}
                                      >
                                        <Copy className="h-3 w-3" />
                                      </Button>
                                    </div>
                                    <div className="font-mono text-sm mt-1">
                                      {password
                                        ? '•••••••••••••••'
                                        : '(Não especificado)'}
                                    </div>
                                  </div>
                                </div>
                              ) : (
                                /* Para registries customizados - Username, Password e Email (se disponível) */
                                <div className="grid grid-cols-2 gap-4">
                                  <div className="bg-white p-3 rounded border">
                                    <div className="flex items-center justify-between">
                                      <span className="text-sm font-medium text-gray-600">
                                        Username:
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => {
                                          navigator.clipboard.writeText(
                                            username,
                                          );
                                          showToast({
                                            title: 'Username Copiado',
                                            description:
                                              'Username copiado para a área de transferência',
                                            variant: 'success',
                                          });
                                        }}
                                      >
                                        <Copy className="h-3 w-3" />
                                      </Button>
                                    </div>
                                    <div
                                      className="font-mono text-sm mt-1 truncate"
                                      title={username}
                                    >
                                      {username || '(Não especificado)'}
                                    </div>
                                  </div>

                                  <div className="bg-white p-3 rounded border">
                                    <div className="flex items-center justify-between">
                                      <span className="text-sm font-medium text-gray-600">
                                        Password:
                                      </span>
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        onClick={() => {
                                          navigator.clipboard.writeText(
                                            password,
                                          );
                                          showToast({
                                            title: 'Password Copiado',
                                            description:
                                              'Password copiado para a área de transferência',
                                            variant: 'success',
                                          });
                                        }}
                                      >
                                        <Copy className="h-3 w-3" />
                                      </Button>
                                    </div>
                                    <div className="font-mono text-sm mt-1">
                                      {password
                                        ? '•••••••••••••••'
                                        : '(Não especificado)'}
                                    </div>
                                  </div>

                                  {email && (
                                    <div className="bg-white p-3 rounded border col-span-2">
                                      <div className="flex items-center justify-between">
                                        <span className="text-sm font-medium text-gray-600">
                                          Email:
                                        </span>
                                        <Button
                                          variant="ghost"
                                          size="sm"
                                          onClick={() => {
                                            navigator.clipboard.writeText(
                                              email,
                                            );
                                            showToast({
                                              title: 'Email Copiado',
                                              description:
                                                'Email copiado para a área de transferência',
                                              variant: 'success',
                                            });
                                          }}
                                        >
                                          <Copy className="h-3 w-3" />
                                        </Button>
                                      </div>
                                      <div
                                        className="font-mono text-sm mt-1 truncate"
                                        title={email}
                                      >
                                        {email}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              )}

                              {config.auth && (
                                <div className="bg-white p-3 rounded border">
                                  <div className="flex items-center justify-between">
                                    <span className="text-sm font-medium text-gray-600">
                                      Auth Token (base64):
                                    </span>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      onClick={() => {
                                        navigator.clipboard.writeText(
                                          config.auth,
                                        );
                                        showToast({
                                          title: 'Token Copiado',
                                          description:
                                            'Token de autenticação copiado para a área de transferência',
                                          variant: 'success',
                                        });
                                      }}
                                    >
                                      <Copy className="h-3 w-3" />
                                    </Button>
                                  </div>
                                  <div
                                    className="font-mono text-xs mt-1 bg-gray-50 p-2 rounded truncate"
                                    title={config.auth}
                                  >
                                    {config.auth}
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>
                        );
                      },
                    );
                  } catch (error) {
                    return (
                      <div className="text-center py-8 text-red-600">
                        Erro ao decodificar credenciais do Docker:{' '}
                        {error instanceof Error
                          ? error.message
                          : 'Erro desconhecido'}
                      </div>
                    );
                  }
                })()}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum dado disponível
              </div>
            )}

            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDockerConfigModalOpen(false)}
              >
                Fechar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </TooltipProvider>
  );
}
