import React, { useState, useMemo, useEffect } from 'react';
import { 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  useDeploymentsInfo,
  useKubectl,
  useClusterEvents,
  useImageDetails,
  ImageDetails,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Layers,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Tag,
  Activity,
  Server,
  Container,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Minus,
  Pause,
  Play,
  Eye,
  Shield,
  Database,
  ChevronDown,
  Key,
  Copy,
} from 'lucide-react';

export function DeploymentsPage() {
  const navigate = useNavigate();
  const {
    deployments,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useDeploymentsInfo();
  const { events: clusterEvents } = useClusterEvents();
  const { executeCommand } = useKubectl();
  const { getImageDetails } = useImageDetails();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deploymentToDelete, setDeploymentToDelete] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [scaleModalOpen, setScaleModalOpen] = useState(false);
  const [deploymentToScale, setDeploymentToScale] = useState<{
    name: string;
    namespace: string;
    currentReplicas: number;
  } | null>(null);
  const [newReplicas, setNewReplicas] = useState<number>(1);
  const [scaling, setScaling] = useState(false);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [deploymentRefreshInterval, setDeploymentRefreshInterval] =
    useState(5000); // 5 segundos
  const [imageModalOpen, setImageModalOpen] = useState(false);
  const [selectedImageDetails, setSelectedImageDetails] =
    useState<ImageDetails | null>(null);
  const [imageDetailsLoading, setImageDetailsLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');

  // Validate that saved namespace still exists, otherwise reset to 'all'
  useEffect(() => {
    if (namespaces.length > 0 && selectedNamespace !== 'all') {
      if (!namespaces.includes(selectedNamespace)) {
        setSelectedNamespace('all');
      }
    }
  }, [namespaces, selectedNamespace, setSelectedNamespace]);

  // Intelligent auto-refresh that waits for previous request to complete
  useEffect(() => {
    if (!autoRefresh) return;

    let timeoutId: NodeJS.Timeout;

    const scheduleNextRefresh = () => {
      timeoutId = setTimeout(async () => {
        // Only refresh if no modals are open and no actions are in progress
        if (
          !deleteModalOpen &&
          !scaleModalOpen &&
          !deleting &&
          !scaling &&
          !actionLoading &&
          !isRefreshing
        ) {
          await backgroundRefetch();
        }
        // Schedule the next refresh after this one completes
        scheduleNextRefresh();
      }, deploymentRefreshInterval);
    };

    // Start the first refresh cycle
    scheduleNextRefresh();

    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [
    autoRefresh,
    deploymentRefreshInterval,
    deleteModalOpen,
    scaleModalOpen,
    deleting,
    scaling,
    actionLoading,
    isRefreshing,
    backgroundRefetch,
  ]);

  const handleDeleteClick = (deploymentName: string, namespaceName: string) => {
    setDeploymentToDelete({ name: deploymentName, namespace: namespaceName });
    setDeleteModalOpen(true);
  };

  const handleScaleClick = (
    deploymentName: string,
    namespaceName: string,
    currentReplicas: number,
  ) => {
    setDeploymentToScale({
      name: deploymentName,
      namespace: namespaceName,
      currentReplicas,
    });
    setNewReplicas(currentReplicas);
    setScaleModalOpen(true);
  };

  const handleConfirmScale = async () => {
    if (!deploymentToScale) return;

    setScaling(true);
    try {
      const command = `kubectl scale deployment ${deploymentToScale.name} --replicas=${newReplicas} -n ${deploymentToScale.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Deployment Escalado',
          description: `O deployment "${deploymentToScale.name}" foi escalado para ${newReplicas} réplica(s)`,
          variant: 'success',
        });
        setScaleModalOpen(false);
        setDeploymentToScale(null);

        // Aguardar 2 segundos antes de atualizar para dar tempo do Kubernetes processar
        setTimeout(async () => {
          await backgroundRefetch();
        }, 2000);
      } 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)); // Máximo de 100 réplicas
  };

  const decrementReplicas = () => {
    setNewReplicas((prev) => Math.max(prev - 1, 0)); // Mínimo de 0 réplicas
  };

  const handleConfirmDelete = async () => {
    if (!deploymentToDelete) return;

    setDeleting(true);
    try {
      const command = `kubectl delete deployment ${deploymentToDelete.name} -n ${deploymentToDelete.namespace}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Deployment Deletado',
          description: `O deployment "${deploymentToDelete.name}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteModalOpen(false);
        setDeploymentToDelete(null);
        await refetch();
      } 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 {
      setDeleting(false);
    }
  };

  const handleDeploymentAction = async (
    deploymentName: string,
    namespaceName: string,
    action: string,
  ) => {
    if (action === 'visualizar') {
      navigate(`/workloads/deployments/${namespaceName}/${deploymentName}`);
      return;
    }

    setActionLoading(`${namespaceName}/${deploymentName}`);
    try {
      let command = '';
      switch (action) {
        case 'describe':
          command = `kubectl describe deployment ${deploymentName} -n ${namespaceName}`;
          break;
        default:
          return;
      }

      const result = await executeCommand(command);
      if (result.success) {
        console.log(`${action} executed successfully:`, result.data);
      } else {
        console.error(`${action} failed:`, result.error);
        showToast({
          title: 'Erro na Operação',
          description: result.error || `Falha ao executar ${action}`,
          variant: 'destructive',
        });
      }
    } catch (err) {
      console.error(`Error executing ${action}:`, err);
      showToast({
        title: 'Erro',
        description: `Erro inesperado ao executar ${action}`,
        variant: 'destructive',
      });
    } finally {
      setActionLoading(null);
    }
  };

  const handleImageClick = async (
    deploymentName: string,
    namespaceName: string,
    imageName: string,
  ) => {
    setImageDetailsLoading(true);
    setImageModalOpen(true);

    try {
      const imageDetails = await getImageDetails(
        deploymentName,
        namespaceName,
        imageName,
      );
      if (imageDetails) {
        setSelectedImageDetails(imageDetails);
      } else {
        showToast({
          title: 'Erro',
          description: 'Não foi possível carregar os detalhes da imagem',
          variant: 'destructive',
        });
      }
    } catch (err) {
      showToast({
        title: 'Erro',
        description: 'Erro ao buscar detalhes da imagem',
        variant: 'destructive',
      });
    } finally {
      setImageDetailsLoading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    showToast({
      title: 'Copiado!',
      description: 'Texto copiado para a área de transferência',
      variant: 'success',
    });
  };

  // Função para obter o estado do deployment (movida para antes do useMemo)
  const getDeploymentState = (deployment: any) => {
    const readyReplicas = deployment.readyReplicas || 0;
    const replicas = deployment.replicas || 0;
    const unavailableReplicas = deployment.unavailableReplicas || 0;
    const conditions = deployment.conditions || [];

    // Função para verificar se condição é recente (últimos 5 minutos)
    const isRecentCondition = (condition: any) => {
      const lastUpdate = new Date(
        condition.lastUpdateTime || condition.lastTransitionTime,
      );
      const now = new Date();
      const diffSeconds = (now.getTime() - lastUpdate.getTime()) / 1000;
      return diffSeconds <= 300; // 5 minutos
    };

    // Verificar eventos recentes de erro relacionados ao deployment
    const recentEvents = clusterEvents.filter((event) => {
      const eventTime = new Date(event.lastTimestamp);
      const now = new Date();
      const diffMinutes = (now.getTime() - eventTime.getTime()) / (1000 * 60);

      return (
        diffMinutes <= 15 && // Últimos 15 minutos
        event.type === 'Warning' &&
        ((event.involvedObject.kind === 'Deployment' &&
          event.involvedObject.name === deployment.name) ||
          (event.involvedObject.kind === 'Pod' &&
            event.involvedObject.namespace === deployment.namespace) ||
          (event.involvedObject.kind === 'ReplicaSet' &&
            event.involvedObject.namespace === deployment.namespace)) &&
        event.involvedObject.namespace === deployment.namespace
      );
    });

    // Verificar eventos críticos
    const hasImagePullErrors = recentEvents.some(
      (e) =>
        e.reason === 'Failed' ||
        e.reason === 'ErrImagePull' ||
        e.reason === 'ImagePullBackOff',
    );

    const hasCrashLoopBackOff = recentEvents.some(
      (e) => e.reason === 'BackOff' || e.message.includes('CrashLoopBackOff'),
    );

    // Estado "Scaled Down" - sem réplicas (PRIORIDADE MÁXIMA)
    if (replicas === 0) {
      return 'scaledDown';
    }

    // Estado "Error" - problemas críticos detectados por eventos
    if (hasImagePullErrors || hasCrashLoopBackOff || deployment.hasPodIssues) {
      return 'error';
    }

    // Estado "Updating" - deployment em atualização
    if (
      (hasImagePullErrors || hasCrashLoopBackOff || deployment.hasPodIssues) &&
      unavailableReplicas > 0
    ) {
      return 'updating';
    }

    // Estado "Ready" - tudo funcionando
    if (
      readyReplicas === replicas &&
      replicas > 0 &&
      !deployment.hasPodIssues
    ) {
      return 'ready';
    }

    // Estado "Partial" - parcialmente funcionando
    if (readyReplicas > 0 && readyReplicas < replicas) {
      return 'partial';
    }

    // Estado "Not Ready" - problemas sérios
    return 'notReady';
  };

  // Filter deployments based on selected namespace, status, and search query
  const filteredDeployments = useMemo(() => {
    let filtered = deployments;

    // Filter by namespace
    if (selectedNamespace !== 'all') {
      filtered = filtered.filter(
        (deployment) => deployment.namespace === selectedNamespace,
      );
    }

    // Filter by status
    if (statusFilter !== 'all') {
      filtered = filtered.filter((deployment) => {
        const state = getDeploymentState(deployment);
        switch (statusFilter) {
          case 'ready':
            return state === 'ready';
          case 'error':
            return state === 'error';
          case 'updating':
            return state === 'updating';
          case 'partial':
            return state === 'partial';
          case 'notReady':
            return state === 'notReady';
          case 'scaledDown':
            return state === 'scaledDown';
          default:
            return true;
        }
      });
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (deployment) =>
          deployment.name.toLowerCase().includes(query) ||
          deployment.namespace.toLowerCase().includes(query) ||
          deployment.images.some((image: string) =>
            image.toLowerCase().includes(query),
          ),
      );
    }

    return filtered;
  }, [deployments, selectedNamespace, statusFilter, searchQuery]);

  const getDeploymentStatus = (deployment: any) => {
    const readyReplicas = deployment.readyReplicas || 0;
    const replicas = deployment.replicas || 0;
    const availableReplicas = deployment.availableReplicas || 0;
    const unavailableReplicas = deployment.unavailableReplicas || 0;
    const updatedReplicas = deployment.updatedReplicas || 0;
    const conditions = deployment.conditions || [];

    // Função para verificar se condição é recente (últimos 2 minutos)
    const isRecentCondition = (condition: any) => {
      const lastUpdate = new Date(
        condition.lastUpdateTime || condition.lastTransitionTime,
      );
      const now = new Date();
      const diffSeconds = (now.getTime() - lastUpdate.getTime()) / 1000;
      return diffSeconds <= 300; // 5 minutos
    };

    // Verificar eventos recentes de erro relacionados ao deployment
    const recentEvents = clusterEvents.filter((event) => {
      const eventTime = new Date(event.lastTimestamp);
      const now = new Date();
      const diffMinutes = (now.getTime() - eventTime.getTime()) / (1000 * 60);

      return (
        diffMinutes <= 15 && // Últimos 15 minutos
        event.type === 'Warning' &&
        ((event.involvedObject.kind === 'Deployment' &&
          event.involvedObject.name === deployment.name) ||
          (event.involvedObject.kind === 'Pod' &&
            event.involvedObject.namespace === deployment.namespace) ||
          (event.involvedObject.kind === 'ReplicaSet' &&
            event.involvedObject.namespace === deployment.namespace)) &&
        event.involvedObject.namespace === deployment.namespace
      );
    });

    // Verificar eventos críticos
    const hasImagePullErrors = recentEvents.some(
      (e) =>
        e.reason === 'Failed' ||
        e.reason === 'ErrImagePull' ||
        e.reason === 'ImagePullBackOff',
    );

    const hasCrashLoopBackOff = recentEvents.some(
      (e) => e.reason === 'BackOff' || e.message.includes('CrashLoopBackOff'),
    );

    // Verifica condições problemáticas
    const progressDeadlineExceeded = conditions.find(
      (c: any) =>
        c.type === 'Progressing' && c.reason === 'ProgressDeadlineExceeded',
      // ProgressDeadlineExceeded não precisa ser recente - é um estado persistente
    );

    const progressingFalse = conditions.find(
      (c: any) => c.type === 'Progressing' && c.status === 'False',
      // Progressing False também persiste até ser resolvido
    );

    const replicaFailure = conditions.find(
      (c: any) =>
        c.type === 'ReplicaFailure' &&
        c.status === 'True' &&
        isRecentCondition(c),
    );

    // ⚪ Estado "Scaled Down" (cinza) - sem réplicas (PRIORIDADE MÁXIMA)
    if (replicas === 0) {
      return <Badge variant="secondary">Scaled Down</Badge>;
    }

    // 🔴 Estado "Error" (vermelho) - problemas críticos detectados por eventos ou pods quebrados
    if (hasImagePullErrors || hasCrashLoopBackOff || deployment.hasPodIssues) {
      return <Badge variant="destructive">Error</Badge>;
    }

    // 🔴 Estado "Updating" (laranja) - muito conservador
    if (
      (hasImagePullErrors || hasCrashLoopBackOff || deployment.hasPodIssues) &&
      unavailableReplicas > 0
    ) {
      return (
        <Badge className="bg-orange-500 hover:bg-orange-600 text-white">
          Updating
        </Badge>
      );
    }

    // 🟢 Estado "Ready" (verde) - mais liberal, mas apenas se não há problemas com pods
    if (
      readyReplicas === replicas &&
      replicas > 0 &&
      !deployment.hasPodIssues
    ) {
      return (
        <Badge className="bg-green-500 hover:bg-green-600 text-white">
          Ready
        </Badge>
      );
    }

    // 🟡 Estado "Partial" (amarelo) - parcialmente funcionando
    if (readyReplicas > 0 && readyReplicas < replicas) {
      return (
        <Badge className="bg-yellow-500 hover:bg-yellow-600 text-white">
          Partial
        </Badge>
      );
    }

    // 🔴 Estado "Not Ready" (vermelho) - problemas sérios
    return <Badge variant="destructive">Not Ready</Badge>;
  };

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

    if (diffDays === 0) {
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      return `${diffHours}h`;
    }
    return `${diffDays} dias`;
  };

  const getImagesList = (images: string[]) => {
    if (images.length === 0) return 'N/A';
    if (images.length === 1) return images[0];
    return `${images[0]} +${images.length - 1}`;
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">Deployments</h1>
            <p className="text-muted-foreground">
              Gerenciar deployments do cluster Kubernetes
            </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 deployments...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">Deployments</h1>
            <p className="text-muted-foreground">
              Gerenciar deployments do cluster Kubernetes
            </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 deployments
            </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 totalDeployments = filteredDeployments.length;

  const readyDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'ready',
  ).length;
  const updatingDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'updating',
  ).length;
  const partialDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'partial',
  ).length;
  const errorDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'error',
  ).length;
  const notReadyDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'notReady',
  ).length;
  const scaledDownDeployments = filteredDeployments.filter(
    (d) => getDeploymentState(d) === 'scaledDown',
  ).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Deployments</h1>
          <p className="text-muted-foreground">
            Gerenciar {totalDeployments} deployment(s){' '}
            {selectedNamespace !== 'all'
              ? `no namespace ${selectedNamespace}`
              : 'em todos os namespaces'}
          </p>
        </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>
                <DropdownMenuItem
                  onClick={() => setDeploymentRefreshInterval(30000)}
                  className={
                    deploymentRefreshInterval === 30000 ? 'bg-green-100' : ''
                  }
                >
                  30 segundos
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Ações de Deployment</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => navigate('/workloads/deployments/create')}
              >
                <Plus className="h-4 w-4 mr-2" />
                Novo
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => navigate('/workloads/deployments/import')}
              >
                <Plus className="h-4 w-4 mr-2" />
                Importar
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total</CardTitle>
            <Layers className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalDeployments}</div>
            <p className="text-xs text-muted-foreground">Deployments</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Ready</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{readyDeployments}</div>
            <p className="text-xs text-muted-foreground">Funcionando</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Error</CardTitle>
            <AlertTriangle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{errorDeployments}</div>
            <p className="text-xs text-muted-foreground">Com erros críticos</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Updating</CardTitle>
            <RefreshCw className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{updatingDeployments}</div>
            <p className="text-xs text-muted-foreground">Em progresso</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Partial</CardTitle>
            <Clock className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{partialDeployments}</div>
            <p className="text-xs text-muted-foreground">
              Parcialmente prontos
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Not Ready</CardTitle>
            <XCircle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{notReadyDeployments}</div>
            <p className="text-xs text-muted-foreground">Com problemas</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filtros
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-4">
            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">
                Namespace
              </label>
              <Select
                value={selectedNamespace}
                onValueChange={setSelectedNamespace}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione um namespace" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os namespaces</SelectItem>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns} value={ns}>
                      {ns}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">Status</label>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Todos os status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os status</SelectItem>
                  <SelectItem value="ready">Ready</SelectItem>
                  <SelectItem value="error">Error</SelectItem>
                  <SelectItem value="updating">Updating</SelectItem>
                  <SelectItem value="partial">Partial</SelectItem>
                  <SelectItem value="notReady">Not Ready</SelectItem>
                  <SelectItem value="scaledDown">Scaled Down</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">Buscar</label>
              <Input
                type="text"
                placeholder="Nome do deployment, namespace, imagem..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Deployments Table */}
      <Card>
        <CardHeader>
          <CardTitle>Lista de Deployments</CardTitle>
          <CardDescription>
            {filteredDeployments.length} deployment(s) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
            {statusFilter !== 'all' && ` com status ${statusFilter}`}
            {searchQuery && ` contendo "${searchQuery}"`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nome</TableHead>
                <TableHead>Namespace</TableHead>
                <TableHead>Ready</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="max-w-xs">Imagens</TableHead>
                <TableHead className="w-24">Idade</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredDeployments.map((deployment, index) => (
                <TableRow key={index} className="h-8">
                  <TableCell className="font-medium">
                    <div
                      className="flex items-center space-x-2 cursor-pointer hover:text-blue-600 transition-colors"
                      onClick={() =>
                        navigate(
                          `/workloads/deployments/${deployment.namespace}/${deployment.name}`,
                        )
                      }
                      title="Clique para ver detalhes"
                    >
                      <Layers className="h-4 w-4 text-blue-600" />
                      <span className="hover:underline">{deployment.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className="text-xs">
                      {deployment.namespace}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-sm">
                    <div className="flex items-center space-x-1">
                      {deployment.readyReplicas === deployment.replicas ? (
                        <CheckCircle className="h-3 w-3 text-green-600" />
                      ) : deployment.readyReplicas > 0 ? (
                        <Clock className="h-3 w-3 text-yellow-600" />
                      ) : (
                        <XCircle className="h-3 w-3 text-red-600" />
                      )}
                      <span>
                        {deployment.readyReplicas}/{deployment.replicas}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>{getDeploymentStatus(deployment)}</TableCell>
                  <TableCell className="text-sm max-w-xs">
                    <div className="flex items-center space-x-1 min-w-0">
                      <Container
                        className="h-3 w-3 text-purple-600 flex-shrink-0 cursor-pointer hover:text-purple-800 transition-colors"
                        onClick={() =>
                          handleImageClick(
                            deployment.name,
                            deployment.namespace,
                            deployment.images[0],
                          )
                        }
                        title="Clique para ver detalhes da imagem"
                      />
                      <span
                        className="truncate"
                        title={deployment.images.join(', ')}
                      >
                        {getImagesList(deployment.images)}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">
                    {getDeploymentAge(deployment.creationTimestamp)}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end space-x-2">
                      {actionLoading ===
                        `${deployment.namespace}/${deployment.name}` && (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      )}
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>
                            Ações do Deployment
                          </DropdownMenuLabel>
                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() =>
                              handleDeploymentAction(
                                deployment.name,
                                deployment.namespace,
                                'visualizar',
                              )
                            }
                            disabled={
                              actionLoading ===
                              `${deployment.namespace}/${deployment.name}`
                            }
                          >
                            <Info className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>

                          <DropdownMenuItem
                            onClick={() =>
                              handleScaleClick(
                                deployment.name,
                                deployment.namespace,
                                deployment.replicas,
                              )
                            }
                            disabled={
                              actionLoading ===
                              `${deployment.namespace}/${deployment.name}`
                            }
                          >
                            <ArrowUpDown className="h-4 w-4 mr-2" />
                            Escalar
                          </DropdownMenuItem>

                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() =>
                              handleDeleteClick(
                                deployment.name,
                                deployment.namespace,
                              )
                            }
                            disabled={
                              actionLoading ===
                              `${deployment.namespace}/${deployment.name}`
                            }
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Deletar
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          {filteredDeployments.length === 0 && (
            <div className="text-center py-8 text-muted-foreground">
              <Layers className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p>Nenhum deployment encontrado</p>
              {(statusFilter !== 'all' ||
                searchQuery ||
                selectedNamespace !== 'all') && (
                <p className="text-sm mt-1">
                  Tente ajustar os filtros para ver mais resultados
                </p>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle className="text-red-600">
              Confirmar Exclusão
            </DialogTitle>
            <DialogDescription>
              Tem certeza que deseja deletar o deployment{' '}
              <strong>"{deploymentToDelete?.name}"</strong> do namespace{' '}
              <strong>"{deploymentToDelete?.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 é irreversível e irá deletar:</p>
                  <ul className="list-disc list-inside mt-2 space-y-1">
                    <li>O deployment e sua configuração</li>
                    <li>Todos os pods gerenciados por este deployment</li>
                    <li>ReplicaSets associados</li>
                    <li>Possível interrupção do serviço</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setDeleteModalOpen(false);
                setDeploymentToDelete(null);
              }}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmDelete}
              disabled={deleting}
            >
              {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {deleting ? 'Deletando...' : 'Sim, Deletar'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 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>"{deploymentToScale?.name}"</strong> no namespace{' '}
              <strong>"{deploymentToScale?.namespace}"</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>{' '}
                  {deploymentToScale?.currentReplicas} réplica(s)
                </div>
                <div>
                  <span className="font-medium">Nova:</span> {newReplicas}{' '}
                  réplica(s)
                </div>
              </div>
              <p className="text-xs text-muted-foreground">
                💡 Dica: 0 réplicas = pausa o serviço, valores altos = mais
                recursos consumidos
              </p>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setScaleModalOpen(false);
                setDeploymentToScale(null);
                setNewReplicas(1);
              }}
              disabled={scaling}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleConfirmScale}
              disabled={
                scaling || newReplicas === deploymentToScale?.currentReplicas
              }
            >
              {scaling && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {scaling ? 'Escalando...' : 'Aplicar'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Image Details Modal */}
      <Dialog open={imageModalOpen} onOpenChange={setImageModalOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center">
              <Container className="h-5 w-5 mr-2 text-purple-600" />
              Detalhes da Imagem
            </DialogTitle>
            <DialogDescription>
              Informações completas sobre a imagem do container
            </DialogDescription>
          </DialogHeader>

          {imageDetailsLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">Carregando detalhes da imagem...</span>
            </div>
          ) : selectedImageDetails ? (
            <div className="space-y-6">
              {/* Image Information */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold flex items-center">
                  <Eye className="h-4 w-4 mr-2" />
                  Informações da Imagem
                </h3>
                <div className="grid grid-cols-1 gap-3">
                  <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div>
                      <span className="font-medium">Nome Completo:</span>
                      <p className="text-sm text-gray-600 break-all">
                        {selectedImageDetails.name}
                      </p>
                    </div>
                    <Copy
                      className="h-4 w-4 cursor-pointer hover:text-blue-600"
                      onClick={() => copyToClipboard(selectedImageDetails.name)}
                      title="Copiar nome da imagem"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Registry:</span>
                      <p className="text-sm text-gray-600">
                        {selectedImageDetails.registry}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Tag:</span>
                      <p className="text-sm text-gray-600">
                        {selectedImageDetails.tag}
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Pull Policy:</span>
                      <p className="text-sm text-gray-600">
                        {selectedImageDetails.pullPolicy}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Repository:</span>
                      <p className="text-sm text-gray-600 break-all">
                        {selectedImageDetails.repository}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Secrets - Only show if there are actually secrets */}
              {selectedImageDetails.secrets &&
              selectedImageDetails.secrets.length > 0 ? (
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Key className="h-4 w-4 mr-2" />
                    Secrets Associados
                  </h3>
                  <div className="space-y-2">
                    {selectedImageDetails.secrets.map((secret, index) => (
                      <div
                        key={index}
                        className="flex items-center justify-between p-3 bg-yellow-50 rounded-lg border border-yellow-200"
                      >
                        <div className="flex items-center">
                          <Shield className="h-4 w-4 mr-2 text-yellow-600" />
                          <span className="font-medium">{secret}</span>
                        </div>
                        <Copy
                          className="h-4 w-4 cursor-pointer hover:text-blue-600"
                          onClick={() => copyToClipboard(secret)}
                          title="Copiar nome do secret"
                        />
                      </div>
                    ))}
                  </div>
                </div>
              ) : (
                // Show a note when no secrets are found
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold flex items-center">
                    <Key className="h-4 w-4 mr-2" />
                    Secrets Associados
                  </h3>
                  <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
                    <p className="text-sm text-gray-600">
                      Nenhum secret de registry configurado para esta imagem
                    </p>
                  </div>
                </div>
              )}

              {/* Ports */}
              {selectedImageDetails.ports &&
                selectedImageDetails.ports.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Server className="h-4 w-4 mr-2" />
                      Portas Expostas
                    </h3>
                    <div className="space-y-2">
                      {selectedImageDetails.ports.map((port, index) => (
                        <div
                          key={index}
                          className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-200"
                        >
                          <div>
                            <span className="font-medium">
                              Porta {port.containerPort}
                            </span>
                            <p className="text-sm text-gray-600">
                              Protocolo: {port.protocol}
                              {port.name && ` | Nome: ${port.name}`}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

              {/* Resources */}
              {selectedImageDetails.resources &&
                Object.keys(selectedImageDetails.resources).length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Zap className="h-4 w-4 mr-2" />
                      Recursos
                    </h3>
                    <div className="grid grid-cols-1 gap-3">
                      {selectedImageDetails.resources.requests && (
                        <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                          <span className="font-medium text-green-800">
                            Requests:
                          </span>
                          <div className="text-sm text-green-700 mt-1">
                            {selectedImageDetails.resources.requests.cpu && (
                              <p>
                                CPU:{' '}
                                {selectedImageDetails.resources.requests.cpu}
                              </p>
                            )}
                            {selectedImageDetails.resources.requests.memory && (
                              <p>
                                Memory:{' '}
                                {selectedImageDetails.resources.requests.memory}
                              </p>
                            )}
                          </div>
                        </div>
                      )}
                      {selectedImageDetails.resources.limits && (
                        <div className="p-3 bg-red-50 rounded-lg border border-red-200">
                          <span className="font-medium text-red-800">
                            Limits:
                          </span>
                          <div className="text-sm text-red-700 mt-1">
                            {selectedImageDetails.resources.limits.cpu && (
                              <p>
                                CPU: {selectedImageDetails.resources.limits.cpu}
                              </p>
                            )}
                            {selectedImageDetails.resources.limits.memory && (
                              <p>
                                Memory:{' '}
                                {selectedImageDetails.resources.limits.memory}
                              </p>
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}

              {/* Environment Variables */}
              {selectedImageDetails.env &&
                selectedImageDetails.env.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Database className="h-4 w-4 mr-2" />
                      Variáveis de Ambiente
                    </h3>
                    <div className="space-y-2 max-h-48 overflow-y-auto">
                      {selectedImageDetails.env.map((envVar, index) => (
                        <div key={index} className="p-3 bg-gray-50 rounded-lg">
                          <div className="flex items-center justify-between">
                            <span className="font-medium">{envVar.name}</span>
                            {envVar.value && (
                              <Copy
                                className="h-4 w-4 cursor-pointer hover:text-blue-600"
                                onClick={() => copyToClipboard(envVar.value!)}
                                title="Copiar valor"
                              />
                            )}
                          </div>
                          <p className="text-sm text-gray-600 mt-1 break-all">
                            {envVar.value ||
                              (envVar.valueFrom
                                ? 'Valor de referência'
                                : 'Não definido')}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

              {/* Volume Mounts */}
              {selectedImageDetails.volumeMounts &&
                selectedImageDetails.volumeMounts.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-lg font-semibold flex items-center">
                      <Archive className="h-4 w-4 mr-2" />
                      Volume Mounts
                    </h3>
                    <div className="space-y-2">
                      {selectedImageDetails.volumeMounts.map((mount, index) => (
                        <div
                          key={index}
                          className="p-3 bg-purple-50 rounded-lg border border-purple-200"
                        >
                          <div className="flex items-center justify-between">
                            <span className="font-medium">{mount.name}</span>
                            <Copy
                              className="h-4 w-4 cursor-pointer hover:text-blue-600"
                              onClick={() => copyToClipboard(mount.mountPath)}
                              title="Copiar path"
                            />
                          </div>
                          <p className="text-sm text-gray-600">
                            Path: {mount.mountPath}
                            {mount.readOnly && ' | Read-Only'}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              Nenhum detalhe da imagem disponível
            </div>
          )}

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