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 {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  ResponsiveContainer,
} from 'recharts';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Progress } from '@/components/ui/progress';
import { LogsModal } from '@/components/ui/logs-modal';
import { usePodDetails, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  ArrowLeft,
  RefreshCw,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Container,
  Layers,
  Activity,
  AlertTriangle,
  Info,
  Terminal,
  FileText,
  Trash2,
  Copy,
  MoreVertical,
  Settings,
  Network,
  Database,
  Shield,
  Cpu,
  MemoryStick,
  HardDrive,
  Eye,
  Tag,
  Server,
  Zap,
  AlertCircle,
  Pause,
  Play,
  TrendingUp,
} from 'lucide-react';

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

  const {
    podInfo,
    containers,
    events,
    metrics,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = usePodDetails(podName || '', namespaceName || '');

  const [autoRefresh, setAutoRefresh] = useState(true);
  const [expandedSections, setExpandedSections] = useState({
    containers: true,
    events: true,
    volumes: true,
  });
  const [deletePodModalOpen, setDeletePodModalOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);
  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);

  // Logs modal states
  const [logsModalOpen, setLogsModalOpen] = useState(false);
  const [selectedContainerForLogs, setSelectedContainerForLogs] = useState<
    string | null
  >(null);

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

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

    // Parse dos valores de CPU e memória
    // CPU pode vir como "100m" (milicores) ou "1.5" (cores)
    let cpuValue = 0;
    if (metrics.cpu.endsWith('m')) {
      // Milicores: "100m" = 0.1 cores
      cpuValue = parseFloat(metrics.cpu.replace('m', '')) / 1000;
    } else {
      // Cores diretos: "1.5" = 1.5 cores
      cpuValue = parseFloat(metrics.cpu);
    }

    // Memória pode vir como "256Mi", "1Gi", "512Ki"
    let memoryValue = 0;
    if (metrics.memory.endsWith('Ki')) {
      // Kilobytes para Mi: dividir por 1024
      memoryValue = parseFloat(metrics.memory.replace('Ki', '')) / 1024;
    } else if (metrics.memory.endsWith('Mi')) {
      // Já está em Mi
      memoryValue = parseFloat(metrics.memory.replace('Mi', ''));
    } else if (metrics.memory.endsWith('Gi')) {
      // Gigabytes para Mi: multiplicar por 1024
      memoryValue = parseFloat(metrics.memory.replace('Gi', '')) * 1024;
    } else {
      // Fallback: assume que já é número
      memoryValue = parseFloat(metrics.memory);
    }

    const now = new Date();
    const timeString = now.toLocaleTimeString('pt-BR', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });

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

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

      return newHistory.slice(-maxHistoryPoints);
    });
  }, [metrics, isBootstrapping]);

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

    const interval = setInterval(() => {
      if (
        !deletePodModalOpen &&
        !deleting &&
        !isRefreshing &&
        !replicaSetModalOpen
      ) {
        backgroundRefetch();
      }
    }, 2000); // 2 segundos durante bootstrap

    return () => clearInterval(interval);
  }, [
    isBootstrapping,
    autoRefresh,
    deletePodModalOpen,
    deleting,
    isRefreshing,
    replicaSetModalOpen,
    backgroundRefetch,
  ]);

  // Auto-refresh normal (10 segundos) - só após bootstrap
  useEffect(() => {
    if (!autoRefresh || isBootstrapping) return; // Pula durante bootstrap

    let timeoutId: NodeJS.Timeout;

    const scheduleNextRefresh = () => {
      timeoutId = setTimeout(async () => {
        if (
          !deletePodModalOpen &&
          !deleting &&
          !isRefreshing &&
          !replicaSetModalOpen
        ) {
          await backgroundRefetch();
        }
        scheduleNextRefresh();
      }, 10000);
    };

    scheduleNextRefresh();

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [
    autoRefresh,
    isBootstrapping,
    deletePodModalOpen,
    deleting,
    isRefreshing,
    replicaSetModalOpen,
    backgroundRefetch,
  ]);

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

  const handlePodLogs = (containerName?: string) => {
    if (!podName || !namespaceName) return;

    setSelectedContainerForLogs(containerName || null);
    setLogsModalOpen(true);
  };

  const handleDeletePod = async () => {
    if (!podName || !namespaceName) return;

    setDeleting(true);
    try {
      const command = `kubectl delete pod ${podName} -n ${namespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Pod Deletado',
          description: `O pod "${podName}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeletePodModalOpen(false);
        // Navegar de volta para a página anterior
        navigate(-1);
      } 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 {
      setDeleting(false);
    }
  };

  const handleReplicaSetClick = async (replicaSetName: string) => {
    if (!replicaSetName || replicaSetName === 'N/A') return;

    setReplicaSetModalOpen(true);
    setLoadingReplicaSetDetails(true);

    try {
      // Buscar detalhes do ReplicaSet, eventos relacionados e todos os pods do namespace
      const [replicaSetRes, eventsRes, podsRes] = await Promise.all([
        executeCommand(
          `kubectl get replicaset ${replicaSetName} -n ${namespaceName} -o json`,
        ),
        executeCommand(
          `kubectl get events -n ${namespaceName} --field-selector involvedObject.kind=ReplicaSet,involvedObject.name=${replicaSetName} --sort-by='.lastTimestamp' -o json`,
        ),
        executeCommand(`kubectl get pods -n ${namespaceName} -o json`),
      ]);

      console.log('ReplicaSet response:', replicaSetRes);
      console.log('Events response:', eventsRes);
      console.log('Pods response:', podsRes);

      // Processar dados do ReplicaSet
      let replicaSetData = null;
      if (replicaSetRes.success) {
        try {
          replicaSetData =
            typeof replicaSetRes.data === 'string'
              ? JSON.parse(replicaSetRes.data)
              : replicaSetRes.data;
          console.log('Parsed ReplicaSet data:', replicaSetData);
          setSelectedReplicaSet(replicaSetData);
        } catch (parseError) {
          console.error('Error parsing ReplicaSet data:', parseError);
        }
      } else {
        console.error('ReplicaSet request failed:', replicaSetRes.error);
      }

      // Processar eventos
      let parsedEvents = [];
      if (eventsRes.success) {
        try {
          const eventsData =
            typeof eventsRes.data === 'string'
              ? JSON.parse(eventsRes.data)
              : eventsRes.data;
          parsedEvents = eventsData.items || [];
          console.log('Parsed events:', parsedEvents);
        } catch (parseError) {
          console.error('Error parsing events data:', parseError);
        }
      }
      setReplicaSetEvents(parsedEvents);

      // Buscar pods relacionados deste ReplicaSet
      let relatedPods = [];
      if (podsRes.success && replicaSetData) {
        try {
          const podsData =
            typeof podsRes.data === 'string'
              ? JSON.parse(podsRes.data)
              : podsRes.data;
          const allPods = podsData.items || [];

          // Filtrar pods que pertencem a este ReplicaSet
          relatedPods = allPods.filter((pod: any) => {
            const ownerRefs = pod.metadata?.ownerReferences || [];
            return ownerRefs.some(
              (ref: any) =>
                ref.kind === 'ReplicaSet' &&
                ref.name === replicaSetName &&
                ref.uid === replicaSetData.metadata?.uid,
            );
          });

          console.log('Related pods found:', relatedPods);
        } catch (parseError) {
          console.error('Error parsing pods data:', parseError);
        }
      }
      setReplicaSetPods(relatedPods);
    } catch (err) {
      console.error('Error fetching ReplicaSet details:', err);
      setSelectedReplicaSet(null);
      setReplicaSetEvents([]);
      setReplicaSetPods([]);
    } finally {
      setLoadingReplicaSetDetails(false);
    }
  };

  const getPodStatus = () => {
    if (!podInfo)
      return { status: 'Unknown', variant: 'secondary' as const, color: '' };

    const phase = podInfo.status?.phase;
    const containerStatuses = podInfo.status?.containerStatuses || [];

    // Verifica se há problemas com containers
    const hasErrors = containerStatuses.some(
      (container: any) =>
        container.state?.waiting?.reason === 'ImagePullBackOff' ||
        container.state?.waiting?.reason === 'ErrImagePull' ||
        container.state?.waiting?.reason === 'CrashLoopBackOff' ||
        container.state?.waiting?.reason === 'CreateContainerConfigError',
    );

    if (hasErrors) {
      return {
        status: 'Error',
        variant: 'destructive' as const,
        color: 'bg-red-500 hover:bg-red-600 text-white',
      };
    }

    switch (phase) {
      case 'Running':
        const readyContainers = containerStatuses.filter(
          (c: any) => c.ready,
        ).length;
        const totalContainers = containerStatuses.length;
        if (readyContainers === totalContainers && totalContainers > 0) {
          return {
            status: 'Running',
            variant: 'default' as const,
            color: 'bg-green-500 hover:bg-green-600 text-white',
          };
        }
        return {
          status: 'Starting',
          variant: 'secondary' as const,
          color: 'bg-orange-500 hover:bg-orange-600 text-white',
        };

      case 'Pending':
        return {
          status: 'Pending',
          variant: 'secondary' as const,
          color: 'bg-yellow-500 hover:bg-yellow-600 text-white',
        };
      case 'Succeeded':
        return {
          status: 'Succeeded',
          variant: 'outline' as const,
          color: 'bg-blue-500 hover:bg-blue-600 text-white',
        };
      case 'Failed':
        return {
          status: 'Failed',
          variant: 'destructive' as const,
          color: 'bg-red-500 hover:bg-red-600 text-white',
        };
      default:
        return {
          status: phase || 'Unknown',
          variant: 'secondary' as const,
          color: '',
        };
    }
  };

  const getPodStatusForList = (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 parseResourceValue = (value: string, type: 'cpu' | 'memory') => {
    if (!value) return 0;

    if (type === 'cpu') {
      // CPU: "100m" = 0.1 cores, "1" = 1 core, "500m" = 0.5 cores
      if (value.endsWith('m')) {
        return parseInt(value) / 1000;
      }
      return parseFloat(value);
    } else {
      // Memory: "256Mi", "1Gi", etc.
      if (value.endsWith('Ki')) {
        return parseInt(value) / 1024; // Convert to Mi
      } else if (value.endsWith('Mi')) {
        return parseInt(value);
      } else if (value.endsWith('Gi')) {
        return parseInt(value) * 1024; // Convert to Mi
      }
      return 0;
    }
  };

  const calculateResourceUsage = (
    currentValue: string,
    requestValue: string | undefined,
    limitValue: string | undefined,
    type: 'cpu' | 'memory',
  ) => {
    if (!currentValue) return null;

    const current = parseResourceValue(currentValue, type);
    const limit = limitValue ? parseResourceValue(limitValue, type) : null;
    const request = requestValue ? parseResourceValue(requestValue, type) : null;

    // Prefer limit, fallback to request for percentage calculation
    const baseValue = limit || request;

    if (!baseValue) {
      return {
        current: currentValue,
        percentage: 0,
        limit: limitValue,
        request: requestValue,
      };
    }

    const percentage = Math.min((current / baseValue) * 100, 100);

    return {
      current: currentValue,
      percentage: Math.round(percentage),
      limit: limitValue,
      request: requestValue,
    };
  };

  const getContainerStatus = (container: any) => {
    if (container.state?.running) {
      return { icon: CheckCircle, color: 'text-green-600', text: 'Running' };
    }
    if (container.state?.waiting) {
      const { reason } = container.state.waiting;
      if (reason === 'ImagePullBackOff' || reason === 'ErrImagePull') {
        return { icon: XCircle, color: 'text-red-600', text: 'Image Error' };
      }
      if (reason === 'CrashLoopBackOff') {
        return { icon: AlertTriangle, color: 'text-red-600', text: 'Crashing' };
      }
      return { icon: Clock, color: 'text-yellow-600', text: reason };
    }
    if (container.state?.terminated) {
      return { icon: XCircle, color: 'text-gray-600', text: 'Terminated' };
    }
    return { icon: AlertTriangle, color: 'text-gray-600', text: 'Unknown' };
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="sm" onClick={() => navigate(-1)}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              Voltar
            </Button>
            <div>
              <h1 className="text-3xl font-bold text-foreground">
                Detalhes do Pod
              </h1>
              <p className="text-muted-foreground">
                Carregando informações do pod...
              </p>
            </div>
          </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 pod...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="sm" onClick={() => navigate(-1)}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              Voltar
            </Button>
            <div>
              <h1 className="text-3xl font-bold text-foreground">
                Detalhes do Pod
              </h1>
              <p className="text-muted-foreground">
                Erro ao carregar informações do pod
              </p>
            </div>
          </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 pod
            </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>
    );
  }

  const podStatus = getPodStatus();

  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">
                <Container className="h-8 w-8 mr-3 text-blue-600" />
                {podName}
              </h1>
              <div className="text-muted-foreground">
                Pod no namespace{' '}
                <Badge variant="outline">{namespaceName}</Badge>
              </div>
            </div>
          </div>
          <div className="flex items-center space-x-2">
            <Button
              onClick={() => setAutoRefresh(!autoRefresh)}
              variant={autoRefresh ? 'default' : 'outline'}
              title={
                autoRefresh
                  ? 'Pausar atualização automática'
                  : 'Ativar atualização automática'
              }
            >
              {autoRefresh ? (
                <>
                  <Pause className="h-4 w-4 mr-2" />
                  Auto (10s)
                </>
              ) : (
                <>
                  <Play className="h-4 w-4 mr-2" />
                  Manual
                </>
              )}
            </Button>
            <Button onClick={refetch} variant="outline" disabled={isRefreshing}>
              <RefreshCw
                className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`}
              />
              Atualizar
            </Button>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline">
                  <MoreVertical className="h-4 w-4 mr-2" />
                  Ações
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>Ações do Pod</DropdownMenuLabel>
                <DropdownMenuSeparator />

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

                <DropdownMenuItem disabled>
                  <FileText className="h-4 w-4 mr-2" />
                  Logs
                </DropdownMenuItem>

                <DropdownMenuSeparator />

                <DropdownMenuItem
                  onClick={() => setDeletePodModalOpen(true)}
                  className="text-red-600"
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  Deletar Pod
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Overview Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-7 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={podStatus.variant}
                className={podStatus.color || ''}
              >
                {podStatus.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">Containers</CardTitle>
              <Container className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {podInfo?.status?.containerStatuses?.filter((c: any) => c.ready)
                  .length || 0}
                /{podInfo?.status?.containerStatuses?.length || 0}
              </div>
              <p className="text-xs text-muted-foreground">Ready/Total</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Restarts</CardTitle>
              <AlertTriangle className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {podInfo?.status?.containerStatuses?.reduce(
                  (sum: number, c: any) => sum + (c.restartCount || 0),
                  0,
                ) || 0}
              </div>
              <p className="text-xs text-muted-foreground">Total restarts</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(podInfo?.metadata?.creationTimestamp || '')}
              </div>
              <p className="text-xs text-muted-foreground">Tempo de vida</p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">QoS</CardTitle>
              <Shield className="h-4 w-4 text-indigo-600" />
            </CardHeader>
            <CardContent>
              <div className="text-lg font-bold">
                {podInfo?.status?.qosClass || 'N/A'}
              </div>
              <p className="text-xs text-muted-foreground">
                Quality of Service
              </p>
            </CardContent>
          </Card>

          {/* CPU Metrics Card */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">CPU</CardTitle>
              <Cpu className="h-4 w-4 text-cyan-600" />
            </CardHeader>
            <CardContent>
              {metrics?.cpu ? (
                <>
                  <div className="text-2xl font-bold">{metrics.cpu}</div>
                  <p className="text-xs text-muted-foreground">cores</p>
                  {(() => {
                    // Calculate total requests/limits from all regular containers (not init containers)
                    const regularContainers = containers.filter(c => !c.isInitContainer);
                    const totalRequest = regularContainers.reduce((sum, c) => {
                      const req = c.resources?.requests?.cpu;
                      return sum + (req ? parseResourceValue(req, 'cpu') : 0);
                    }, 0);
                    const totalLimit = regularContainers.reduce((sum, c) => {
                      const lim = c.resources?.limits?.cpu;
                      return sum + (lim ? parseResourceValue(lim, 'cpu') : 0);
                    }, 0);

                    if (totalLimit > 0 || totalRequest > 0) {
                      const usage = calculateResourceUsage(
                        metrics.cpu,
                        totalRequest > 0 ? `${totalRequest}` : undefined,
                        totalLimit > 0 ? `${totalLimit}` : undefined,
                        'cpu',
                      );

                      if (usage) {
                        return (
                          <div className="mt-2">
                            <Progress
                              value={Math.min(usage.percentage, 100)}
                              className="h-1"
                            />
                            <p className="text-xs text-muted-foreground mt-1">
                              {usage.percentage}% de {usage.limit || usage.request}
                            </p>
                          </div>
                        );
                      }
                    }
                    return (
                      <p className="text-xs text-muted-foreground mt-1">
                        Sem limites definidos
                      </p>
                    );
                  })()}
                </>
              ) : (
                <>
                  <div className="text-sm text-muted-foreground">N/A</div>
                  <p className="text-xs text-muted-foreground">
                    Metrics server indisponível
                  </p>
                </>
              )}
            </CardContent>
          </Card>

          {/* Memory Metrics Card */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Memória</CardTitle>
              <MemoryStick className="h-4 w-4 text-pink-600" />
            </CardHeader>
            <CardContent>
              {metrics?.memory ? (
                <>
                  <div className="text-2xl font-bold">{metrics.memory}</div>
                  <p className="text-xs text-muted-foreground">usado</p>
                  {(() => {
                    // Calculate total requests/limits from all regular containers (not init containers)
                    const regularContainers = containers.filter(c => !c.isInitContainer);
                    const totalRequest = regularContainers.reduce((sum, c) => {
                      const req = c.resources?.requests?.memory;
                      return sum + (req ? parseResourceValue(req, 'memory') : 0);
                    }, 0);
                    const totalLimit = regularContainers.reduce((sum, c) => {
                      const lim = c.resources?.limits?.memory;
                      return sum + (lim ? parseResourceValue(lim, 'memory') : 0);
                    }, 0);

                    if (totalLimit > 0 || totalRequest > 0) {
                      const usage = calculateResourceUsage(
                        metrics.memory,
                        totalRequest > 0 ? `${totalRequest}Mi` : undefined,
                        totalLimit > 0 ? `${totalLimit}Mi` : undefined,
                        'memory',
                      );

                      if (usage) {
                        return (
                          <div className="mt-2">
                            <Progress
                              value={Math.min(usage.percentage, 100)}
                              className="h-1"
                            />
                            <p className="text-xs text-muted-foreground mt-1">
                              {usage.percentage}% de {usage.limit || usage.request}
                            </p>
                          </div>
                        );
                      }
                    }
                    return (
                      <p className="text-xs text-muted-foreground mt-1">
                        Sem limites definidos
                      </p>
                    );
                  })()}
                </>
              ) : (
                <>
                  <div className="text-sm text-muted-foreground">N/A</div>
                  <p className="text-xs text-muted-foreground">
                    Metrics server indisponível
                  </p>
                </>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Real-time Metrics Graphs */}
        {metrics?.cpu && metrics?.memory && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <TrendingUp className="h-5 w-5 mr-2" />
                Métricas em Tempo Real
              </CardTitle>
              <CardDescription>
                Utilização de CPU e Memória nos últimos{' '}
                {Math.floor((maxHistoryPoints * 10) / 60)} minutos (atualiza a
                cada 10s)
              </CardDescription>
            </CardHeader>
            <CardContent>
              {metricsHistory.length < 2 ? (
                <div className="flex items-center justify-center py-12 text-muted-foreground">
                  <Loader2 className="h-6 w-6 animate-spin mr-2" />
                  Coletando dados das métricas...
                </div>
              ) : (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  {/* CPU Chart */}
                  <div className="space-y-2">
                    <h3 className="text-sm font-medium text-muted-foreground">
                      CPU (cores)
                    </h3>
                    <ResponsiveContainer width="100%" height={250}>
                      <AreaChart data={metricsHistory}>
                        <defs>
                          <linearGradient
                            id="colorCpuPod"
                            x1="0"
                            y1="0"
                            x2="0"
                            y2="1"
                          >
                            <stop
                              offset="5%"
                              stopColor="#10b981"
                              stopOpacity={0.3}
                            />
                            <stop
                              offset="95%"
                              stopColor="#10b981"
                              stopOpacity={0}
                            />
                          </linearGradient>
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" opacity={0.3} />
                        <XAxis
                          dataKey="time"
                          tick={{ fontSize: 11 }}
                          angle={-45}
                          textAnchor="end"
                          height={60}
                        />
                        <YAxis
                          domain={[0, 'auto']}
                          tick={{ fontSize: 11 }}
                          tickFormatter={(value) => value.toFixed(2)}
                        />
                        <RechartsTooltip
                          contentStyle={{
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            color: 'white',
                            borderRadius: '6px',
                            border: 'none',
                          }}
                          labelStyle={{ color: '#10b981' }}
                          formatter={(value: any) => [
                            `${value.toFixed(3)} cores`,
                            'CPU',
                          ]}
                        />
                        <Area
                          type="monotone"
                          dataKey="cpu"
                          stroke="#10b981"
                          strokeWidth={2}
                          fill="url(#colorCpuPod)"
                          isAnimationActive={false}
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  </div>

                  {/* Memory Chart */}
                  <div className="space-y-2">
                    <h3 className="text-sm font-medium text-muted-foreground">
                      Memória (Mi)
                    </h3>
                    <ResponsiveContainer width="100%" height={250}>
                      <AreaChart data={metricsHistory}>
                        <defs>
                          <linearGradient
                            id="colorMemoryPod"
                            x1="0"
                            y1="0"
                            x2="0"
                            y2="1"
                          >
                            <stop
                              offset="5%"
                              stopColor="#a855f7"
                              stopOpacity={0.3}
                            />
                            <stop
                              offset="95%"
                              stopColor="#a855f7"
                              stopOpacity={0}
                            />
                          </linearGradient>
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" opacity={0.3} />
                        <XAxis
                          dataKey="time"
                          tick={{ fontSize: 11 }}
                          angle={-45}
                          textAnchor="end"
                          height={60}
                        />
                        <YAxis
                          domain={[0, 'auto']}
                          tick={{ fontSize: 11 }}
                          tickFormatter={(value) => Math.round(value)}
                        />
                        <RechartsTooltip
                          contentStyle={{
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            color: 'white',
                            borderRadius: '6px',
                            border: 'none',
                          }}
                          labelStyle={{ color: '#a855f7' }}
                          formatter={(value: any) => [
                            `${Math.round(value)} Mi`,
                            'Memória',
                          ]}
                        />
                        <Area
                          type="monotone"
                          dataKey="memory"
                          stroke="#a855f7"
                          strokeWidth={2}
                          fill="url(#colorMemoryPod)"
                          isAnimationActive={false}
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Pod Details */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Container className="h-5 w-5 mr-2 text-blue-600" />
              Informações Gerais
            </CardTitle>
            <CardDescription>
              Detalhes técnicos e configurações do pod
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {/* Coluna 1: IP, ReplicaSet, Deployment */}
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      IP do Pod:
                    </span>
                    <div className="flex items-center space-x-2 group">
                      <span className="font-mono text-sm font-medium">
                        {podInfo?.status?.podIP || 'N/A'}
                      </span>
                      {podInfo?.status?.podIP && (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-4 w-4 p-0 hover:bg-gray-100 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                          onClick={() => {
                            navigator.clipboard.writeText(podInfo.status.podIP);
                            showToast({
                              title: 'IP Copiado',
                              description: `IP ${podInfo.status.podIP} copiado para a área de transferência`,
                              variant: 'success',
                            });
                          }}
                          title="Copiar IP"
                        >
                          <Copy className="h-3 w-3" />
                        </Button>
                      )}
                    </div>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      ReplicaSet:
                    </span>
                    <div className="flex items-center space-x-2 group">
                      {(() => {
                        const ownerRefs =
                          podInfo?.metadata?.ownerReferences || [];
                        const replicaSetRef = ownerRefs.find(
                          (ref: any) => ref.kind === 'ReplicaSet',
                        );
                        const replicaSetName = replicaSetRef?.name;

                        if (replicaSetName && replicaSetName !== 'N/A') {
                          return (
                            <>
                              <span
                                className="text-sm font-medium font-mono text-xs cursor-pointer hover:text-blue-600 transition-colors hover:underline"
                                onClick={() =>
                                  handleReplicaSetClick(replicaSetName)
                                }
                                title="Clique para ver detalhes do ReplicaSet"
                              >
                                {replicaSetName}
                              </span>
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 p-0 hover:bg-gray-100 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                                onClick={() => {
                                  navigator.clipboard.writeText(replicaSetName);
                                  showToast({
                                    title: 'ReplicaSet Copiado',
                                    description: `ReplicaSet "${replicaSetName}" copiado para a área de transferência`,
                                    variant: 'success',
                                  });
                                }}
                                title="Copiar ReplicaSet"
                              >
                                <Copy className="h-3 w-3" />
                              </Button>
                            </>
                          );
                        }

                        return (
                          <span className="text-sm font-medium font-mono text-xs">
                            N/A
                          </span>
                        );
                      })()}
                    </div>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Deployment:
                    </span>
                    <div className="flex items-center space-x-2 group">
                      {(() => {
                        // Busca pelo deployment através dos owner references
                        const ownerRefs =
                          podInfo?.metadata?.ownerReferences || [];
                        const replicaSetRef = ownerRefs.find(
                          (ref: any) => ref.kind === 'ReplicaSet',
                        );
                        if (replicaSetRef) {
                          // Extrai o nome do deployment do nome do ReplicaSet
                          const rsName = replicaSetRef.name;
                          const deploymentName = rsName.substring(
                            0,
                            rsName.lastIndexOf('-'),
                          );
                          if (deploymentName && deploymentName !== 'N/A') {
                            return (
                              <>
                                <span
                                  className="text-sm font-medium cursor-pointer hover:text-blue-600 transition-colors hover:underline"
                                  onClick={() =>
                                    navigate(
                                      `/workloads/deployments/${namespaceName}/${deploymentName}`,
                                    )
                                  }
                                  title="Clique para ver detalhes do deployment"
                                >
                                  {deploymentName}
                                </span>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-4 w-4 p-0 hover:bg-gray-100 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                                  onClick={() => {
                                    navigator.clipboard.writeText(
                                      deploymentName,
                                    );
                                    showToast({
                                      title: 'Deployment Copiado',
                                      description: `Deployment "${deploymentName}" copiado para a área de transferência`,
                                      variant: 'success',
                                    });
                                  }}
                                  title="Copiar Deployment"
                                >
                                  <Copy className="h-3 w-3" />
                                </Button>
                              </>
                            );
                          }
                        }
                        return <span className="text-sm font-medium">N/A</span>;
                      })()}
                    </div>
                  </div>
                </div>

                {/* Coluna 2: Namespace, Service Account, Node */}
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Namespace:
                    </span>
                    <Badge variant="outline" className="text-xs">
                      {namespaceName}
                    </Badge>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Service Account:
                    </span>
                    <span className="text-sm font-medium">
                      {podInfo?.spec?.serviceAccountName || 'default'}
                    </span>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">Node:</span>
                    <div className="flex items-center space-x-1">
                      <Server className="h-3 w-3 text-muted-foreground" />
                      {podInfo?.spec?.nodeName &&
                      podInfo.spec.nodeName !== 'N/A' ? (
                        <span
                          className="text-sm font-medium cursor-pointer hover:text-blue-600 transition-colors hover:underline"
                          onClick={() =>
                            navigate(`/cluster/nodes/${podInfo.spec.nodeName}`)
                          }
                          title="Clique para ver detalhes do node"
                        >
                          {podInfo.spec.nodeName}
                        </span>
                      ) : (
                        <span className="text-sm font-medium">N/A</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Coluna 3: Data de Criação, Tempo, Restart Policy */}
                <div className="space-y-3">
                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Data de Criação:
                    </span>
                    <div className="flex items-center space-x-1">
                      <Calendar className="h-3 w-3 text-muted-foreground" />
                      <span className="text-sm font-medium">
                        {new Date(
                          podInfo?.metadata?.creationTimestamp || '',
                        ).toLocaleDateString('pt-BR')}
                      </span>
                    </div>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Tempo:
                    </span>
                    <div className="flex items-center space-x-1">
                      <Clock className="h-3 w-3 text-muted-foreground" />
                      <span className="text-sm font-medium">
                        {getAge(podInfo?.metadata?.creationTimestamp || '')}
                      </span>
                    </div>
                  </div>

                  <div className="flex justify-between">
                    <span className="text-sm text-muted-foreground">
                      Restart Policy:
                    </span>
                    <Badge variant="outline" className="text-xs">
                      {podInfo?.spec?.restartPolicy || 'Always'}
                    </Badge>
                  </div>
                </div>
              </div>

              {/* Labels Section - Full Width */}
              {Object.keys(podInfo?.metadata?.labels || {}).length > 0 && (
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <Tag className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm font-medium text-muted-foreground">
                      Labels do Pod:
                    </span>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {Object.entries(podInfo?.metadata?.labels || {}).map(
                      ([key, value]) => (
                        <Badge
                          key={key}
                          variant="secondary"
                          className="text-xs"
                        >
                          {key}: {value as string}
                        </Badge>
                      ),
                    )}
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Containers 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" />
                Containers ({containers.length})
              </CardTitle>
            </div>
            <CardDescription>Containers em execução neste pod</CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Nome</TableHead>
                  <TableHead>Imagem</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Ready</TableHead>
                  <TableHead>Restarts</TableHead>
                  <TableHead>Portas</TableHead>
                  <TableHead>Recursos</TableHead>
                  <TableHead>Tipo</TableHead>
                  <TableHead className="text-right">Ações</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {containers.map((container: any, index: number) => {
                  // Buscar status no array correto baseado no tipo de container
                  const containerStatus = container.isInitContainer
                    ? podInfo?.status?.initContainerStatuses?.find(
                        (cs: any) => cs.name === container.name,
                      )
                    : podInfo?.status?.containerStatuses?.find(
                        (cs: any) => cs.name === container.name,
                      );

                  const status = containerStatus
                    ? getContainerStatus(containerStatus)
                    : {
                        icon: AlertTriangle,
                        color: 'text-gray-600',
                        text: 'Unknown',
                      };

                  return (
                    <TableRow key={index}>
                      <TableCell className="font-medium">
                        {container.name}
                      </TableCell>
                      <TableCell
                        className="max-w-xs truncate"
                        title={container.image}
                      >
                        {container.image}
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <status.icon className={`h-4 w-4 ${status.color}`} />
                          <span className={`text-sm ${status.color}`}>
                            {status.text}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        {containerStatus?.ready ? (
                          <CheckCircle className="h-4 w-4 text-green-600" />
                        ) : (
                          <XCircle className="h-4 w-4 text-red-600" />
                        )}
                      </TableCell>
                      <TableCell>
                        {containerStatus?.restartCount || 0}
                      </TableCell>
                      <TableCell>
                        {container.ports?.length > 0 ? (
                          <div className="space-y-1">
                            {container.ports
                              .slice(0, 2)
                              .map((port: any, portIndex: number) => (
                                <Badge
                                  key={portIndex}
                                  variant="outline"
                                  className="text-xs"
                                >
                                  {port.containerPort}/{port.protocol || 'TCP'}
                                </Badge>
                              ))}
                            {container.ports.length > 2 && (
                              <span className="text-xs text-muted-foreground">
                                +{container.ports.length - 2} mais
                              </span>
                            )}
                          </div>
                        ) : (
                          'N/A'
                        )}
                      </TableCell>
                      <TableCell>
                        {container.resources?.requests ||
                        container.resources?.limits ? (
                          <div className="space-y-1 text-xs">
                            {container.resources.requests?.cpu && (
                              <div>CPU: {container.resources.requests.cpu}</div>
                            )}
                            {container.resources.requests?.memory && (
                              <div>
                                Mem: {container.resources.requests.memory}
                              </div>
                            )}
                          </div>
                        ) : (
                          'N/A'
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            container.isInitContainer ? 'secondary' : 'outline'
                          }
                          className={
                            container.isInitContainer
                              ? 'bg-orange-100 text-orange-800'
                              : 'bg-purple-100 text-purple-800'
                          }
                        >
                          {container.isInitContainer ? 'Init' : 'Regular'}
                        </Badge>
                      </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 Container
                            </DropdownMenuLabel>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={() => {
                                // Abrir modal de logs para este container específico
                                handlePodLogs(container.name);
                              }}
                            >
                              <FileText className="h-4 w-4 mr-2" />
                              Ver Logs
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Events Section */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Activity className="h-5 w-5 mr-2 text-green-600" />
              Eventos ({events.length})
            </CardTitle>
            <CardDescription>
              Eventos recentes relacionados ao pod
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Tipo</TableHead>
                  <TableHead>Razão</TableHead>
                  <TableHead>Mensagem</TableHead>
                  <TableHead>Idade</TableHead>
                  <TableHead>Count</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {events.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.lastTimestamp || event.eventTime || '')}
                    </TableCell>
                    <TableCell>{event.count || 1}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {events.length === 0 && (
              <div className="text-center py-8 text-muted-foreground">
                Nenhum evento encontrado
              </div>
            )}
          </CardContent>
        </Card>

        {/* 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 = getPodStatusForList(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
                        .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>

        {/* 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>"{podName}"</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>Terminar permanentemente este pod</li>
                      <li>Parar todos os containers em execução</li>
                      <li>Perder todos os dados não persistidos</li>
                      <li>Esta ação não pode ser desfeita</li>
                      <li>O deployment pode recriar o pod automaticamente</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDeletePodModalOpen(false)}
                disabled={deleting}
              >
                Cancelar
              </Button>
              <Button
                variant="destructive"
                onClick={handleDeletePod}
                disabled={deleting}
              >
                {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                {deleting ? 'Deletando...' : 'Sim, Deletar'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Logs Modal */}
        <LogsModal
          open={logsModalOpen}
          onOpenChange={setLogsModalOpen}
          podName={podName || ''}
          containerName={selectedContainerForLogs || undefined}
          namespace={namespaceName || ''}
          title="Logs do Container"
        />
      </div>
    </TooltipProvider>
  );
}
