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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useSecretsInfo, useKubectl, SecretInfo } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Key,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Tag,
  Activity,
  Server,
  Container,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Minus,
  Pause,
  Play,
  Eye,
  Shield,
  Database,
  Copy,
  FileText,
  Settings,
  Lock,
  ChevronDown,
  Upload,
  ClipboardCopy,
} from 'lucide-react';

export function SecretsPage() {
  const navigate = useNavigate();
  const {
    secrets,
    namespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = useSecretsInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [sortField, setSortField] = useState<string>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [secretRefreshInterval, setSecretRefreshInterval] = useState(7000); // 7 segundos

  // Modal states
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedSecret, setSelectedSecret] = useState<SecretInfo | null>(null);
  const [deleting, setDeleting] = useState(false);

  // Clone modal states
  const [cloneModalOpen, setCloneModalOpen] = useState(false);
  const [secretToClone, setSecretToClone] = useState<SecretInfo | null>(null);
  const [cloneTargetNamespace, setCloneTargetNamespace] = useState('');
  const [cloneNewName, setCloneNewName] = useState('');
  const [cloning, setCloning] = useState(false);

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

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

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

  // Filter and sort secrets
  const filteredAndSortedSecrets = useMemo(() => {
    let filtered = secrets;

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

    // Filter by type
    if (typeFilter !== 'all') {
      filtered = filtered.filter((secret) => secret.type === typeFilter);
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (secret) =>
          secret.name.toLowerCase().includes(query) ||
          secret.namespace.toLowerCase().includes(query) ||
          secret.type.toLowerCase().includes(query) ||
          (secret.data &&
            Object.keys(secret.data).some((key) =>
              key.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 'type':
          aValue = a.type;
          bValue = b.type;
          break;
        case 'dataCount':
          aValue = a.dataCount;
          bValue = b.dataCount;
          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;
    });
  }, [
    secrets,
    selectedNamespace,
    typeFilter,
    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 getSecretTypeColor = (type: string) => {
    switch (type) {
      case 'Opaque':
        return 'bg-blue-100 text-blue-800';
      case 'kubernetes.io/service-account-token':
        return 'bg-green-100 text-green-800';
      case 'kubernetes.io/dockercfg':
      case 'kubernetes.io/dockerconfigjson':
        return 'bg-purple-100 text-purple-800';
      case 'kubernetes.io/tls':
        return 'bg-orange-100 text-orange-800';
      case 'kubernetes.io/ssh-auth':
        return 'bg-yellow-100 text-yellow-800';
      case 'kubernetes.io/basic-auth':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getSecretTypeDisplay = (type: string) => {
    switch (type) {
      case 'Opaque':
        return 'Opaque';
      case 'kubernetes.io/service-account-token':
        return 'Service Account';
      case 'kubernetes.io/dockercfg':
        return 'Docker CFG';
      case 'kubernetes.io/dockerconfigjson':
        return 'Docker Config';
      case 'kubernetes.io/tls':
        return 'TLS';
      case 'kubernetes.io/ssh-auth':
        return 'SSH Auth';
      case 'kubernetes.io/basic-auth':
        return 'Basic Auth';
      default:
        return type;
    }
  };

  const handleDeleteSecret = async () => {
    if (!selectedSecret) return;

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

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

        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Excluir Secret',
          description: result.error || 'Falha ao excluir o Secret',
          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);
      setSelectedSecret(null);
    }
  };

  const handleDeleteClick = (secret: SecretInfo) => {
    setSelectedSecret(secret);
    setDeleteModalOpen(true);
  };

  // Functions for cloning secrets
  const handleCloneClick = (secret: SecretInfo) => {
    console.log('🔍 Available namespaces for clone:', namespaces);
    console.log('🔍 Current secret namespace:', secret.namespace);
    setSecretToClone(secret);
    setCloneNewName(secret.name);
    setCloneTargetNamespace('');
    setCloneModalOpen(true);
  };

  const handleCloneSecret = async () => {
    if (!secretToClone || !cloneTargetNamespace || !cloneNewName) return;

    setCloning(true);
    try {
      // 1. Buscar os dados completos do secret original
      const getSecretCommand = `kubectl get secret ${secretToClone.name} -n ${secretToClone.namespace} -o yaml`;
      const getResult = await executeCommand(getSecretCommand);

      if (!getResult.success) {
        throw new Error(getResult.error || 'Falha ao obter dados do secret');
      }

      // 2. Parse do YAML e preparação dos dados
      const secretData = getResult.data;
      
      // 3. Criar comando para aplicar o secret clonado
      // Remove metadados específicos e atualiza nome/namespace
      const cleanedYaml = secretData
        .replace(/^  resourceVersion:.*$/m, '')
        .replace(/^  uid:.*$/m, '')
        .replace(/^  creationTimestamp:.*$/m, '')
        .replace(/^  selfLink:.*$/m, '')
        .replace(/^  generation:.*$/m, '')
        .replace(/^metadata:\s*\n  name:.*$/m, `metadata:\n  name: ${cloneNewName}`)
        .replace(/^  namespace:.*$/m, `  namespace: ${cloneTargetNamespace}`)
        // Se não tinha namespace, adiciona
        .replace(/^metadata:\s*\n  name:.*$/m, `metadata:\n  name: ${cloneNewName}\n  namespace: ${cloneTargetNamespace}`);

      // 4. Aplicar o secret clonado
      const applyCommand = `echo '${cleanedYaml}' | kubectl apply -f -`;
      const applyResult = await executeCommand(applyCommand);

      if (applyResult.success) {
        showToast({
          title: 'Secret Clonado',
          description: `Secret "${cloneNewName}" criado com sucesso no namespace "${cloneTargetNamespace}"`,
          variant: 'success',
        });
        setCloneModalOpen(false);
        setSecretToClone(null);
        setCloneNewName('');
        setCloneTargetNamespace('');
        // Refresh para mostrar o novo secret se estamos vendo o namespace de destino
        if (selectedNamespace === 'all' || selectedNamespace === cloneTargetNamespace) {
          await refetch();
        }
      } else {
        throw new Error(applyResult.error || 'Falha ao criar secret clonado');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro ao Clonar Secret',
        description: errorMessage,
        variant: 'destructive',
      });
    } finally {
      setCloning(false);
    }
  };

  const handleCancelClone = () => {
    setCloneModalOpen(false);
    setSecretToClone(null);
    setCloneNewName('');
    setCloneTargetNamespace('');
  };

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

    return {
      total: filtered.length,
      opaque: filtered.filter((secret) => secret.type === 'Opaque').length,
      serviceAccount: filtered.filter(
        (secret) => secret.type === 'kubernetes.io/service-account-token',
      ).length,
      tls: filtered.filter((secret) => secret.type === 'kubernetes.io/tls')
        .length,
      docker: filtered.filter(
        (secret) =>
          secret.type === 'kubernetes.io/dockercfg' ||
          secret.type === 'kubernetes.io/dockerconfigjson',
      ).length,
    };
  }, [secrets, 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 Secrets...</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">
            <Key className="h-8 w-8 mr-3 text-blue-600" />
            Secrets
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os Secrets 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 ({secretRefreshInterval / 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={() => setSecretRefreshInterval(1000)}
                  className={
                    secretRefreshInterval === 1000 ? 'bg-green-100' : ''
                  }
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setSecretRefreshInterval(3000)}
                  className={
                    secretRefreshInterval === 3000 ? 'bg-green-100' : ''
                  }
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setSecretRefreshInterval(5000)}
                  className={
                    secretRefreshInterval === 5000 ? 'bg-green-100' : ''
                  }
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setSecretRefreshInterval(7000)}
                  className={
                    secretRefreshInterval === 7000 ? 'bg-green-100' : ''
                  }
                >
                  7 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setSecretRefreshInterval(10000)}
                  className={
                    secretRefreshInterval === 10000 ? 'bg-green-100' : ''
                  }
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setSecretRefreshInterval(30000)}
                  className={
                    secretRefreshInterval === 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 Secret</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/secrets/new')}>
                <Plus className="h-4 w-4 mr-2" />
                Nova
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => navigate('/storage/secrets/import')}>
                <Upload 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-5 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>
            <Key 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">Secrets 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">Opaque</CardTitle>
            <Lock className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {statusStats.opaque}
            </div>
            <p className="text-xs text-muted-foreground">Genéricos</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Service Account
            </CardTitle>
            <Shield className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.serviceAccount}
            </div>
            <p className="text-xs text-muted-foreground">Contas de serviço</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">TLS</CardTitle>
            <Settings className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {statusStats.tls}
            </div>
            <p className="text-xs text-muted-foreground">Certificados</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Docker</CardTitle>
            <Container className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {statusStats.docker}
            </div>
            <p className="text-xs text-muted-foreground">Credenciais</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">Tipo</label>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Todos os tipos" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os tipos</SelectItem>
                  <SelectItem value="Opaque">Opaque</SelectItem>
                  <SelectItem value="kubernetes.io/service-account-token">
                    Service Account
                  </SelectItem>
                  <SelectItem value="kubernetes.io/tls">TLS</SelectItem>
                  <SelectItem value="kubernetes.io/dockercfg">
                    Docker CFG
                  </SelectItem>
                  <SelectItem value="kubernetes.io/dockerconfigjson">
                    Docker Config
                  </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, tipo, chave..."
                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>

      {/* Secrets Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedSecrets.length} Secret(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('type')}
                  >
                    Tipo
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('dataCount')}
                  >
                    Data Keys
                    <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>
              {filteredAndSortedSecrets.map((secret) => {
                return (
                  <TableRow key={`${secret.namespace}-${secret.name}`}>
                    <TableCell>
                      <button
                        className="text-blue-600 hover:text-blue-800 hover:underline text-left font-medium"
                        onClick={() =>
                          navigate(
                            `/storage/secrets/${secret.namespace}/${secret.name}`,
                          )
                        }
                      >
                        {secret.name}
                      </button>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{secret.namespace}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getSecretTypeColor(secret.type)}>
                        {getSecretTypeDisplay(secret.type)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{secret.dataCount}</Badge>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-muted-foreground">
                        {getAge(secret.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(
                                `/storage/secrets/${secret.namespace}/${secret.name}`,
                              )
                            }
                          >
                            <Eye className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => handleCloneClick(secret)}
                          >
                            <ClipboardCopy className="h-4 w-4 mr-2" />
                            Clonar
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() => handleDeleteClick(secret)}
                            className="text-red-600"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Excluir
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
              {filteredAndSortedSecrets.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8">
                    <div className="text-muted-foreground">
                      <Key className="h-8 w-8 mx-auto mb-2 opacity-50" />
                      <p>Nenhum Secret encontrado</p>
                      {(typeFilter !== '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>

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

      {/* Clone Secret Modal */}
      <Dialog open={cloneModalOpen} onOpenChange={setCloneModalOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>Clonar Secret</DialogTitle>
            <DialogDescription>
              Clone o Secret{' '}
              <strong>{secretToClone?.name}</strong> do namespace{' '}
              <strong>{secretToClone?.namespace}</strong> para outro namespace.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="clone-name">Nome do novo Secret</Label>
              <Input
                id="clone-name"
                value={cloneNewName}
                onChange={(e) => setCloneNewName(e.target.value)}
                placeholder="Ex: meu-secret-copy"
                disabled={cloning}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="target-namespace">Namespace de destino</Label>
              <Select
                value={cloneTargetNamespace}
                onValueChange={setCloneTargetNamespace}
                disabled={cloning}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione o namespace de destino..." />
                </SelectTrigger>
                <SelectContent>
                  {namespaces.map((namespace) => (
                    <SelectItem 
                      key={namespace} 
                      value={namespace}
                      disabled={namespace === secretToClone?.namespace}
                    >
                      {namespace} {namespace === secretToClone?.namespace && "(atual)"}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {secretToClone && (
              <div className="mt-2 p-3 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground">
                  <strong>Informações do Secret original:</strong>
                </p>
                <p className="text-sm">Tipo: {secretToClone.type}</p>
                <p className="text-sm">Chaves: {secretToClone.keys} chave(s)</p>
                <p className="text-sm">Criado em: {new Date(secretToClone.creationTimestamp).toLocaleDateString('pt-BR')}</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={handleCancelClone}
              disabled={cloning}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleCloneSecret}
              disabled={cloning || !cloneTargetNamespace || !cloneNewName}
            >
              {cloning ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Clonando...
                </>
              ) : (
                <>
                  <ClipboardCopy className="h-4 w-4 mr-2" />
                  Clonar Secret
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
