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 {
  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 {
  useStatefulSetsInfo,
  useKubectl,
  useClusterEvents,
  useImageDetails,
  ImageDetails,
  StatefulSetInfo,
} from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Database,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Tag,
  Activity,
  Server,
  Container,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Minus,
  Pause,
  Play,
  Eye,
  Shield,
  Key,
  Copy,
  ChevronDown,
} from 'lucide-react';

export function StatefulSetsPage() {
  const navigate = useNavigate();
  const {
    statefulSets,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useStatefulSetsInfo();
  const { events: clusterEvents } = useClusterEvents();
  const { executeCommand } = useKubectl();
  const { getImageDetails } = useImageDetails();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [sortField, setSortField] = useState<string>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [statefulSetRefreshInterval, setStatefulSetRefreshInterval] =
    useState(6000); // 6 segundos

  // Modal states
  const [scaleModalOpen, setScaleModalOpen] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [imageDetailsModalOpen, setImageDetailsModalOpen] = useState(false);
  const [selectedStatefulSet, setSelectedStatefulSet] =
    useState<StatefulSetInfo | null>(null);
  const [newReplicaCount, setNewReplicaCount] = useState<number>(1);
  const [scaling, setScaling] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [selectedImageDetails, setSelectedImageDetails] =
    useState<ImageDetails | null>(null);
  const [imageDetailsLoading, setImageDetailsLoading] = useState(false);

  // Auto-refresh effect
  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(() => {
      backgroundRefetch();
    }, statefulSetRefreshInterval);

    return () => clearInterval(interval);
  }, [autoRefresh, statefulSetRefreshInterval, backgroundRefetch]);

  // Filter and sort statefulsets
  const filteredAndSortedStatefulSets = useMemo(() => {
    let filtered = statefulSets;

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

    // Filter by status
    if (statusFilter !== 'all') {
      filtered = filtered.filter((sts) => {
        const status = sts.status.toLowerCase();
        return status === statusFilter.toLowerCase();
      });
    }

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

    // Sort
    return filtered.sort((a, b) => {
      let aValue: any;
      let bValue: any;

      switch (sortField) {
        case 'name':
          aValue = a.name;
          bValue = b.name;
          break;
        case 'namespace':
          aValue = a.namespace;
          bValue = b.namespace;
          break;
        case 'replicas':
          aValue = a.replicas;
          bValue = b.replicas;
          break;
        case 'ready':
          aValue = a.readyReplicas;
          bValue = b.readyReplicas;
          break;
        case 'status':
          aValue = a.status;
          bValue = b.status;
          break;
        case 'age':
          aValue = new Date(a.creationTimestamp).getTime();
          bValue = new Date(b.creationTimestamp).getTime();
          break;
        default:
          aValue = a.name;
          bValue = b.name;
      }

      if (sortDirection === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      }
      return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
    });
  }, [
    statefulSets,
    selectedNamespace,
    statusFilter,
    searchQuery,
    sortField,
    sortDirection,
  ]);

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

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

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

  const getStatefulSetStatus = (statefulSet: StatefulSetInfo) => {
    if (statefulSet.hasPodIssues) {
      return {
        label: 'Issues',
        color: 'text-red-600',
        bgColor: 'bg-red-100',
        icon: XCircle,
      };
    }

    if (statefulSet.readyReplicas === statefulSet.replicas) {
      return {
        label: 'Ready',
        color: 'text-green-600',
        bgColor: 'bg-green-100',
        icon: CheckCircle,
      };
    }

    return {
      label: 'Not Ready',
      color: 'text-yellow-600',
      bgColor: 'bg-yellow-100',
      icon: Clock,
    };
  };

  const handleScaleStatefulSet = async () => {
    if (!selectedStatefulSet) return;

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

      if (result.success) {
        showToast({
          title: 'StatefulSet Escalado',
          description: `StatefulSet "${selectedStatefulSet.name}" foi escalado para ${newReplicaCount} réplicas`,
          variant: 'success',
        });

        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Escalar StatefulSet',
          description: result.error || 'Falha ao escalar o StatefulSet',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setScaling(false);
      setScaleModalOpen(false);
      setSelectedStatefulSet(null);
    }
  };

  const handleDeleteStatefulSet = async () => {
    if (!selectedStatefulSet) return;

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

      if (result.success) {
        showToast({
          title: 'StatefulSet Excluído',
          description: `StatefulSet "${selectedStatefulSet.name}" foi excluído com sucesso`,
          variant: 'success',
        });

        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Excluir StatefulSet',
          description: result.error || 'Falha ao excluir o StatefulSet',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
      setDeleteModalOpen(false);
      setSelectedStatefulSet(null);
    }
  };

  const handleScaleClick = (statefulSet: StatefulSetInfo) => {
    setSelectedStatefulSet(statefulSet);
    setNewReplicaCount(statefulSet.replicas);
    setScaleModalOpen(true);
  };

  const handleDeleteClick = (statefulSet: StatefulSetInfo) => {
    setSelectedStatefulSet(statefulSet);
    setDeleteModalOpen(true);
  };

  const statusStats = useMemo(() => {
    const filtered =
      selectedNamespace === 'all'
        ? statefulSets
        : statefulSets.filter((sts) => sts.namespace === selectedNamespace);

    return {
      total: filtered.length,
      ready: filtered.filter(
        (sts) => sts.readyReplicas === sts.replicas && !sts.hasPodIssues,
      ).length,
      notReady: filtered.filter(
        (sts) => sts.readyReplicas !== sts.replicas || sts.hasPodIssues,
      ).length,
      withIssues: filtered.filter((sts) => sts.hasPodIssues).length,
    };
  }, [statefulSets, selectedNamespace]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-muted-foreground">Carregando StatefulSets...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <AlertCircle className="h-8 w-8 text-red-500 mx-auto mb-4" />
          <p className="text-red-600 mb-4">{error}</p>
          <Button onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Tentar Novamente
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center">
            <Database className="h-8 w-8 mr-3 text-blue-600" />
            StatefulSets
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os StatefulSets do cluster
          </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 ({statefulSetRefreshInterval / 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={() => setStatefulSetRefreshInterval(1000)}
                  className={
                    statefulSetRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setStatefulSetRefreshInterval(3000)}
                  className={
                    statefulSetRefreshInterval === 3000 ? 'bg-green-100' : ''
                  }
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setStatefulSetRefreshInterval(5000)}
                  className={
                    statefulSetRefreshInterval === 5000 ? 'bg-green-100' : ''
                  }
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setStatefulSetRefreshInterval(6000)}
                  className={
                    statefulSetRefreshInterval === 6000 ? 'bg-green-100' : ''
                  }
                >
                  6 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setStatefulSetRefreshInterval(10000)}
                  className={
                    statefulSetRefreshInterval === 10000 ? 'bg-green-100' : ''
                  }
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setStatefulSetRefreshInterval(30000)}
                  className={
                    statefulSetRefreshInterval === 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 StatefulSet</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => navigate('/workloads/statefulsets/import')}
              >
                <Plus className="h-4 w-4 mr-2" />
                Importar
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 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>
            <Database className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statusStats.total}</div>
            <p className="text-xs text-muted-foreground">
              StatefulSets no cluster
            </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 text-green-600">
              {statusStats.ready}
            </div>
            <p className="text-xs text-muted-foreground">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>
            <Clock className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {statusStats.notReady}
            </div>
            <p className="text-xs text-muted-foreground">Não 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">With Issues</CardTitle>
            <XCircle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">
              {statusStats.withIssues}
            </div>
            <p className="text-xs text-muted-foreground">Com problemas</p>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <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="not ready">Not Ready</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, namespace, imagem..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* StatefulSets Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedStatefulSets.length} StatefulSet(s) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('name')}
                  >
                    Nome
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('namespace')}
                  >
                    Namespace
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('ready')}
                  >
                    Ready
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('replicas')}
                  >
                    Réplicas
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('status')}
                  >
                    Status
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('age')}
                  >
                    Idade
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredAndSortedStatefulSets.map((statefulSet) => {
                const status = getStatefulSetStatus(statefulSet);
                const StatusIcon = status.icon;

                return (
                  <TableRow
                    key={`${statefulSet.namespace}-${statefulSet.name}`}
                  >
                    <TableCell>
                      <button
                        className="text-blue-600 hover:text-blue-800 hover:underline text-left font-medium"
                        onClick={() =>
                          navigate(
                            `/workloads/statefulsets/${statefulSet.namespace}/${statefulSet.name}`,
                          )
                        }
                      >
                        {statefulSet.name}
                      </button>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{statefulSet.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">
                        {statefulSet.readyReplicas}/{statefulSet.replicas}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm">{statefulSet.replicas}</span>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center">
                        <StatusIcon
                          className={`h-4 w-4 mr-2 ${status.color}`}
                        />
                        <Badge className={`${status.bgColor} ${status.color}`}>
                          {status.label}
                        </Badge>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(statefulSet.creationTimestamp)}
                      </span>
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                          >
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>Ações</DropdownMenuLabel>
                          <DropdownMenuItem
                            onClick={() =>
                              navigate(
                                `/workloads/statefulsets/${statefulSet.namespace}/${statefulSet.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => handleScaleClick(statefulSet)}
                          >
                            <Zap className="h-4 w-4 mr-2" />
                            Escalar
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(statefulSet)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedStatefulSets.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <Database className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum StatefulSet encontrado</p>
                      {(statusFilter !== 'all' ||
                        searchQuery ||
                        selectedNamespace !== 'all') && (
                        <p className="text-sm mt-1">
                          Tente ajustar os filtros para ver mais resultados
                        </p>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Scale Modal */}
      <Dialog open={scaleModalOpen} onOpenChange={setScaleModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Escalar StatefulSet</DialogTitle>
            <DialogDescription>
              Altere o número de réplicas do StatefulSet{' '}
              <strong>{selectedStatefulSet?.name}</strong> em{' '}
              <strong>{selectedStatefulSet?.namespace}</strong>.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <label className="text-sm font-medium mb-2 block">
              Número de Réplicas
            </label>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="icon"
                onClick={() =>
                  setNewReplicaCount(Math.max(0, newReplicaCount - 1))
                }
                disabled={newReplicaCount <= 0}
              >
                <Minus className="h-4 w-4" />
              </Button>
              <input
                type="number"
                min="0"
                value={newReplicaCount}
                onChange={(e) =>
                  setNewReplicaCount(parseInt(e.target.value) || 0)
                }
                className="w-20 px-3 py-2 border rounded-md text-center focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <Button
                variant="outline"
                size="icon"
                onClick={() => setNewReplicaCount(newReplicaCount + 1)}
              >
                <Plus className="h-4 w-4" />
              </Button>
            </div>
            <p className="text-xs text-muted-foreground mt-2">
              Réplicas atuais: {selectedStatefulSet?.replicas}
            </p>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setScaleModalOpen(false)}
              disabled={scaling}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleScaleStatefulSet}
              disabled={
                scaling || newReplicaCount === selectedStatefulSet?.replicas
              }
            >
              {scaling ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Escalando...
                </>
              ) : (
                <>
                  <Zap className="h-4 w-4 mr-2" />
                  Escalar
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir StatefulSet</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o StatefulSet{' '}
              <strong>{selectedStatefulSet?.name}</strong> do namespace{' '}
              <strong>{selectedStatefulSet?.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e todos os pods associados serão
              removidos.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteStatefulSet}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir StatefulSet
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
