import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { YamlEditor } from '@/components/ui/yaml-editor';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  Key,
  AlertCircle,
  RefreshCw,
  ArrowLeft,
  MoreVertical,
  Trash2,
  FileText,
  Settings,
  Copy,
  Calendar,
  Tag,
  Database,
  Info,
  Edit3,
  Eye,
  Download,
  ExternalLink,
  Shield,
  Lock,
  Container,
  Globe,
  User,
} from 'lucide-react';

interface SecretData {
  name: string;
  namespace: string;
  type: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  data: Record<string, string>;
  resourceVersion: string;
  uid: string;
}

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

  const [secret, setSecret] = useState<SecretData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showYaml, setShowYaml] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const fetchSecretDetails = async () => {
    if (!namespaceName || !secretName) return;

    try {
      setLoading(true);
      setError(null);

      const command = `kubectl get secret ${secretName} -n ${namespaceName} -o json`;
      const result = await executeCommand(command);

      if (result.success) {
        const data = JSON.parse(result.data);
        setSecret({
          name: data.metadata.name,
          namespace: data.metadata.namespace,
          type: data.type,
          creationTimestamp: data.metadata.creationTimestamp,
          labels: data.metadata.labels || {},
          annotations: data.metadata.annotations || {},
          data: data.data || {},
          resourceVersion: data.metadata.resourceVersion,
          uid: data.metadata.uid,
        });
      } else {
        setError(result.error || 'Falha ao buscar detalhes do Secret');
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const fetchYaml = () => {
    setShowYaml(true);
  };

  const handleDeleteSecret = async () => {
    if (!namespaceName || !secretName) return;

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

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

        navigate('/storage/secrets');
      } 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);
    }
  };

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

  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 getSecretTypeIcon = (type: string) => {
    switch (type) {
      case 'kubernetes.io/service-account-token':
        return Shield;
      case 'kubernetes.io/dockercfg':
      case 'kubernetes.io/dockerconfigjson':
        return Container;
      case 'kubernetes.io/tls':
        return FileText;
      case 'kubernetes.io/ssh-auth':
        return Key;
      case 'kubernetes.io/basic-auth':
        return User;
      default:
        return Lock;
    }
  };

  const decodeBase64 = (encodedString: string): string => {
    try {
      return atob(encodedString);
    } catch (err) {
      return '[Não foi possível decodificar]';
    }
  };

  const renderSecretData = () => {
    if (!secret || Object.keys(secret.data).length === 0) {
      return (
        <div className="text-center py-8 text-muted-foreground">
          <Database className="h-8 w-8 mx-auto mb-2 opacity-50" />
          <p>Nenhum dado encontrado</p>
        </div>
      );
    }

    // Para TLS certificates
    if (secret.type === 'kubernetes.io/tls') {
      return (
        <div className="space-y-4">
          <div className="flex items-center mb-4">
            <FileText className="h-5 w-5 mr-2 text-orange-600" />
            <span className="font-medium">Certificado TLS</span>
          </div>
          {Object.entries(secret.data).map(([key, value]) => (
            <Card key={key}>
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-base flex items-center">
                    {key === 'tls.crt' && <FileText className="h-4 w-4 mr-2" />}
                    {key === 'tls.key' && <Key className="h-4 w-4 mr-2" />}
                    {key}
                  </CardTitle>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => copyToClipboard(decodeBase64(value))}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <pre className="text-sm whitespace-pre-wrap break-words font-mono bg-muted p-3 rounded max-h-96 overflow-y-auto">
                  {decodeBase64(value)}
                </pre>
              </CardContent>
            </Card>
          ))}
        </div>
      );
    }

    // Para Docker configs
    if (
      secret.type === 'kubernetes.io/dockerconfigjson' ||
      secret.type === 'kubernetes.io/dockercfg'
    ) {
      return (
        <div className="space-y-4">
          <div className="flex items-center mb-4">
            <Container className="h-5 w-5 mr-2 text-purple-600" />
            <span className="font-medium">Configuração Docker</span>
          </div>
          {Object.entries(secret.data).map(([key, value]) => (
            <Card key={key}>
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-base">{key}</CardTitle>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => copyToClipboard(decodeBase64(value))}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <pre className="text-sm whitespace-pre-wrap break-words font-mono bg-muted p-3 rounded max-h-96 overflow-y-auto">
                  {decodeBase64(value)}
                </pre>
              </CardContent>
            </Card>
          ))}
        </div>
      );
    }

    // Para Service Account tokens
    if (secret.type === 'kubernetes.io/service-account-token') {
      return (
        <div className="space-y-4">
          <div className="flex items-center mb-4">
            <Shield className="h-5 w-5 mr-2 text-green-600" />
            <span className="font-medium">Token de Service Account</span>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Chave</TableHead>
                <TableHead>Tipo</TableHead>
                <TableHead>Valor</TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {Object.entries(secret.data).map(([key, value]) => (
                <TableRow key={key}>
                  <TableCell>
                    <div className="flex items-center">
                      <Badge variant="outline" className="mr-2">
                        {key}
                      </Badge>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary">
                      {key === 'token'
                        ? 'JWT Token'
                        : key === 'ca.crt'
                          ? 'Certificate'
                          : key === 'namespace'
                            ? 'Text'
                            : 'Binary'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="max-w-md">
                      {key === 'token' ? (
                        <span className="text-xs text-muted-foreground">
                          [Token JWT - {value.length} caracteres]
                        </span>
                      ) : key === 'namespace' ? (
                        <span className="text-sm font-mono">
                          {decodeBase64(value)}
                        </span>
                      ) : (
                        <span className="text-xs text-muted-foreground">
                          [Certificado - {value.length} caracteres]
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => copyToClipboard(decodeBase64(value))}
                    >
                      <Copy className="h-3 w-3" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      );
    }

    // Para tipos genéricos (Opaque, basic-auth, ssh-auth)
    return (
      <Tabs defaultValue="table" className="w-full">
        <TabsList>
          <TabsTrigger value="table">Tabela</TabsTrigger>
          <TabsTrigger value="raw">Texto</TabsTrigger>
        </TabsList>

        <TabsContent value="table" className="mt-4">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Chave</TableHead>
                <TableHead>Valor</TableHead>
                <TableHead className="w-16">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {Object.entries(secret.data).map(([key, value]) => (
                <TableRow key={key}>
                  <TableCell>
                    <div className="flex items-center">
                      <Badge variant="outline" className="mr-2">
                        {key}
                      </Badge>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={() => copyToClipboard(key)}
                      >
                        <Copy className="h-3 w-3" />
                      </Button>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="max-w-md">
                      <pre className="text-xs whitespace-pre-wrap break-words font-mono bg-muted p-2 rounded">
                        {decodeBase64(value) || '(vazio)'}
                      </pre>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => copyToClipboard(decodeBase64(value))}
                    >
                      <Copy className="h-3 w-3" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TabsContent>

        <TabsContent value="raw" className="mt-4">
          <div className="space-y-4">
            {Object.entries(secret.data).map(([key, value]) => (
              <Card key={key}>
                <CardHeader className="pb-2">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base">{key}</CardTitle>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => copyToClipboard(decodeBase64(value))}
                    >
                      <Copy className="h-3 w-3" />
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <pre className="text-sm whitespace-pre-wrap break-words font-mono bg-muted p-3 rounded max-h-96 overflow-y-auto">
                    {decodeBase64(value) || '(vazio)'}
                  </pre>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>
      </Tabs>
    );
  };

  useEffect(() => {
    fetchSecretDetails();
  }, [namespaceName, secretName]);

  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 detalhes do Secret...
          </p>
        </div>
      </div>
    );
  }

  if (error || !secret) {
    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 || 'Secret não encontrado'}
          </p>
          <div className="space-x-2">
            <Button onClick={() => fetchSecretDetails()}>
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar Novamente
            </Button>
            <Button
              variant="outline"
              onClick={() => navigate('/storage/secrets')}
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Voltar
            </Button>
          </div>
        </div>
      </div>
    );
  }

  const SecretIcon = getSecretTypeIcon(secret.type);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-foreground flex items-center">
              <Key className="h-8 w-8 mr-3 text-blue-600" />
              {secret.name}
            </h1>
            <div className="text-muted-foreground">
              Secret no namespace{' '}
              <Badge variant="outline" className="mx-1">
                {secret.namespace}
              </Badge>
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline">
                <MoreVertical className="h-4 w-4 mr-2" />
                Ações
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Navegação</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate('/storage/secrets')}>
                <ExternalLink className="h-4 w-4 mr-2" />
                Lista de Secrets
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Informações Gerais */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Info className="h-5 w-5 mr-2" />
              Informações Gerais
            </div>
            <div className="flex gap-2">
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button onClick={fetchYaml} variant="outline" size="sm">
                      <Eye className="h-4 w-4 mr-2" />
                      YAML
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Visualizar YAML completo</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      onClick={() =>
                        copyToClipboard(JSON.stringify(secret, null, 2))
                      }
                      variant="outline"
                      size="sm"
                    >
                      <Copy className="h-4 w-4 mr-2" />
                      JSON
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Copiar dados como JSON</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      onClick={() => setDeleteModalOpen(true)}
                      variant="destructive"
                      size="sm"
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      Excluir
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Excluir este Secret</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Nome
              </label>
              <div className="flex items-center justify-between mt-1">
                <span className="text-sm font-medium">{secret.name}</span>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(secret.name)}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Namespace
              </label>
              <div className="flex items-center justify-between mt-1">
                <Badge variant="outline">{secret.namespace}</Badge>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(secret.namespace)}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Tipo
              </label>
              <div className="mt-1">
                <Badge className={getSecretTypeColor(secret.type)}>
                  <SecretIcon className="h-3 w-3 mr-1" />
                  {getSecretTypeDisplay(secret.type)}
                </Badge>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Criado há
              </label>
              <div className="mt-1">
                <span className="text-sm">
                  {getAge(secret.creationTimestamp)}
                </span>
              </div>
            </div>
          </div>

          <div className="mt-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  UID
                </label>
                <div className="flex items-center justify-between mt-1">
                  <span className="text-sm font-mono">{secret.uid}</span>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => copyToClipboard(secret.uid)}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Resource Version
                </label>
                <div className="mt-1">
                  <span className="text-sm">{secret.resourceVersion}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Labels e Annotations lado a lado */}
          {(Object.keys(secret.labels).length > 0 ||
            Object.keys(secret.annotations).length > 0) && (
            <div className="mt-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Labels */}
                {Object.keys(secret.labels).length > 0 && (
                  <div>
                    <label className="text-sm font-medium text-muted-foreground flex items-center mb-3">
                      <Tag className="h-4 w-4 mr-2" />
                      Labels
                    </label>
                    <div className="space-y-2">
                      {Object.entries(secret.labels).map(([key, value]) => (
                        <div
                          key={key}
                          className="flex items-center justify-between p-2 bg-muted rounded"
                        >
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium truncate">
                              {key}
                            </div>
                            <div className="text-xs text-muted-foreground truncate">
                              {value}
                            </div>
                          </div>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => copyToClipboard(`${key}=${value}`)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Annotations */}
                {Object.keys(secret.annotations).length > 0 && (
                  <div>
                    <label className="text-sm font-medium text-muted-foreground flex items-center mb-3">
                      <Settings className="h-4 w-4 mr-2" />
                      Annotations
                    </label>
                    <div className="space-y-2">
                      {Object.entries(secret.annotations).map(
                        ([key, value]) => (
                          <div
                            key={key}
                            className="flex items-center justify-between p-2 bg-muted rounded"
                          >
                            <div className="flex-1 min-w-0">
                              <div className="text-sm font-medium truncate">
                                {key}
                              </div>
                              <div className="text-xs text-muted-foreground truncate">
                                {value}
                              </div>
                            </div>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => copyToClipboard(`${key}=${value}`)}
                            >
                              <Copy className="h-3 w-3" />
                            </Button>
                          </div>
                        ),
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Dados do Secret */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Database className="h-5 w-5 mr-2" />
            Dados do Secret
          </CardTitle>
          <CardDescription>
            {Object.keys(secret.data).length} chave(s) • Tipo:{' '}
            {getSecretTypeDisplay(secret.type)}
          </CardDescription>
        </CardHeader>
        <CardContent>{renderSecretData()}</CardContent>
      </Card>

      {/* YAML Modal */}
      <YamlEditor
        open={showYaml}
        onOpenChange={setShowYaml}
        resourceType="secret"
        resourceName={secret.name}
        namespace={secret.namespace}
        title={`YAML do Secret - ${secret.name}`}
      />

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir Secret</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o Secret{' '}
              <strong>{secret.name}</strong> do namespace{' '}
              <strong>{secret.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>
    </div>
  );
}
