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,
  Globe,
  AlertCircle,
  RefreshCw,
  ArrowLeft,
  MoreVertical,
  Trash2,
  FileText,
  Settings,
  Copy,
  Calendar,
  Tag,
  Database,
  Info,
  Edit3,
  Eye,
  Download,
  ExternalLink,
  Shield,
  Lock,
  Network,
  Route,
  Server,
  MapPin,
  CheckCircle,
  Clock,
  AlertTriangle,
} from 'lucide-react';

interface IngressData {
  name: string;
  namespace: string;
  className?: string;
  creationTimestamp: string;
  labels: Record<string, string>;
  annotations: Record<string, string>;
  rules: IngressRule[];
  tls: IngressTLS[];
  addresses: string[];
  resourceVersion: string;
  uid: string;
}

interface IngressRule {
  host?: string;
  http: {
    paths: IngressPath[];
  };
}

interface IngressPath {
  path?: string;
  pathType: string;
  backend: {
    service?: {
      name: string;
      port: {
        number?: number;
        name?: string;
      };
    };
  };
}

interface IngressTLS {
  hosts: string[];
  secretName?: string;
}

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

  const [ingress, setIngress] = useState<IngressData | 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 fetchIngressDetails = async () => {
    if (!namespaceName || !ingressName) return;

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

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

      if (result.success) {
        const data = JSON.parse(result.data);
        setIngress({
          name: data.metadata.name,
          namespace: data.metadata.namespace,
          className: data.spec?.ingressClassName,
          creationTimestamp: data.metadata.creationTimestamp,
          labels: data.metadata.labels || {},
          annotations: data.metadata.annotations || {},
          rules: data.spec?.rules || [],
          tls: data.spec?.tls || [],
          addresses:
            data.status?.loadBalancer?.ingress
              ?.map((lb: any) => lb.ip || lb.hostname)
              .filter(Boolean) || [],
          resourceVersion: data.metadata.resourceVersion,
          uid: data.metadata.uid,
        });
      } else {
        setError(result.error || 'Falha ao buscar detalhes do Ingress');
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  };

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

  const handleDeleteIngress = async () => {
    if (!namespaceName || !ingressName) return;

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

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

        navigate('/service-discovery/ingresses');
      } else {
        showToast({
          title: 'Erro ao Excluir Ingress',
          description: result.error || 'Falha ao excluir o Ingress',
          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 getIngressStatus = () => {
    if (!ingress)
      return {
        label: 'Unknown',
        color: 'text-gray-600',
        bgColor: 'bg-gray-100',
        icon: AlertTriangle,
      };

    if (ingress.addresses.length > 0) {
      return {
        label: 'Ready',
        color: 'text-green-600',
        bgColor: 'bg-green-100',
        icon: CheckCircle,
      };
    }

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

  const getAllHosts = () => {
    if (!ingress) return [];
    return [...new Set(ingress.rules.map((rule) => rule.host).filter(Boolean))];
  };

  const getAllPaths = () => {
    if (!ingress) return [];
    const paths: Array<{
      host?: string;
      path?: string;
      pathType: string;
      serviceName: string;
      servicePort: string | number;
    }> = [];

    ingress.rules.forEach((rule) => {
      rule.http?.paths?.forEach((path) => {
        if (path.backend.service) {
          paths.push({
            host: rule.host,
            path: path.path,
            pathType: path.pathType,
            serviceName: path.backend.service.name,
            servicePort:
              path.backend.service.port.number ||
              path.backend.service.port.name ||
              '',
          });
        }
      });
    });

    return paths;
  };

  const getTLSHosts = () => {
    if (!ingress) return [];
    return ingress.tls.flatMap((tls) => tls.hosts);
  };

  const openExternalUrl = (host: string) => {
    const protocol = getTLSHosts().includes(host) ? 'https' : 'http';
    window.open(`${protocol}://${host}`, '_blank');
  };

  useEffect(() => {
    fetchIngressDetails();
  }, [namespaceName, ingressName]);

  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 Ingress...
          </p>
        </div>
      </div>
    );
  }

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

  const status = getIngressStatus();
  const StatusIcon = status.icon;
  const allHosts = getAllHosts();
  const allPaths = getAllPaths();
  const tlsHosts = getTLSHosts();

  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">
              <Globe className="h-8 w-8 mr-3 text-blue-600" />
              {ingress.name}
            </h1>
            <div className="text-muted-foreground">
              Ingress no namespace{' '}
              <Badge variant="outline" className="mx-1">
                {ingress.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('/service-discovery/ingresses')}
              >
                <ExternalLink className="h-4 w-4 mr-2" />
                Lista de Ingresses
              </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(ingress, 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 Ingress</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">{ingress.name}</span>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(ingress.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">{ingress.namespace}</Badge>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => copyToClipboard(ingress.namespace)}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Status
              </label>
              <div className="mt-1">
                <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>
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-muted-foreground">
                Criado há
              </label>
              <div className="mt-1">
                <span className="text-sm">
                  {getAge(ingress.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">{ingress.uid}</span>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => copyToClipboard(ingress.uid)}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">
                  Ingress Class
                </label>
                <div className="mt-1">
                  <span className="text-sm">{ingress.className || '-'}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Labels e Annotations lado a lado */}
          {(Object.keys(ingress.labels).length > 0 ||
            Object.keys(ingress.annotations).length > 0) && (
            <div className="mt-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Labels */}
                {Object.keys(ingress.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(ingress.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(ingress.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(ingress.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>

      {/* Configuração de Roteamento */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Route className="h-5 w-5 mr-2" />
            Configuração de Roteamento
          </CardTitle>
          <CardDescription>
            {allPaths.length} rota(s) configurada(s) em {allHosts.length}{' '}
            host(s)
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="paths" className="w-full">
            <TabsList>
              <TabsTrigger value="paths">Rotas</TabsTrigger>
              <TabsTrigger value="hosts">Hosts</TabsTrigger>
              {ingress.tls.length > 0 && (
                <TabsTrigger value="tls">TLS</TabsTrigger>
              )}
            </TabsList>

            <TabsContent value="paths" className="mt-4">
              {allPaths.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Host</TableHead>
                      <TableHead>Path</TableHead>
                      <TableHead>Path Type</TableHead>
                      <TableHead>Service</TableHead>
                      <TableHead>Port</TableHead>
                      <TableHead className="w-16">Ações</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {allPaths.map((pathConfig, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          <div className="flex items-center">
                            <Badge variant="outline" className="mr-2">
                              {pathConfig.host || '*'}
                            </Badge>
                            {pathConfig.host && (
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-6 w-6"
                                onClick={() =>
                                  pathConfig.host &&
                                  openExternalUrl(pathConfig.host)
                                }
                                title="Abrir no navegador"
                              >
                                <ExternalLink className="h-3 w-3" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <code className="text-sm">
                            {pathConfig.path || '/'}
                          </code>
                        </TableCell>
                        <TableCell>
                          <Badge variant="secondary">
                            {pathConfig.pathType}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <span className="font-mono text-sm">
                            {pathConfig.serviceName}
                          </span>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline">
                            {pathConfig.servicePort}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() =>
                              copyToClipboard(
                                `${pathConfig.host}${pathConfig.path} -> ${pathConfig.serviceName}:${pathConfig.servicePort}`,
                              )
                            }
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <Route className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Nenhuma rota configurada</p>
                </div>
              )}
            </TabsContent>

            <TabsContent value="hosts" className="mt-4">
              {allHosts.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {allHosts.map((host, index) => (
                    <Card key={index} className="p-4">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center">
                          <Globe className="h-4 w-4 mr-2 text-blue-600" />
                          <span className="font-medium">{host}</span>
                          {tlsHosts.includes(host) && (
                            <Shield
                              className="h-3 w-3 ml-2 text-green-600"
                              title="TLS Habilitado"
                            />
                          )}
                        </div>
                        <div className="flex space-x-1">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => openExternalUrl(host)}
                            title="Abrir no navegador"
                          >
                            <ExternalLink className="h-3 w-3" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-6 w-6"
                            onClick={() => copyToClipboard(host)}
                          >
                            <Copy className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <Globe className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Nenhum host configurado</p>
                </div>
              )}
            </TabsContent>

            {ingress.tls.length > 0 && (
              <TabsContent value="tls" className="mt-4">
                <div className="space-y-4">
                  {ingress.tls.map((tls, index) => (
                    <Card key={index}>
                      <CardHeader className="pb-2">
                        <div className="flex items-center justify-between">
                          <CardTitle className="text-base flex items-center">
                            <Shield className="h-4 w-4 mr-2 text-green-600" />
                            Configuração TLS #{index + 1}
                          </CardTitle>
                          {tls.secretName && (
                            <Badge variant="outline">{tls.secretName}</Badge>
                          )}
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-2">
                          <div>
                            <label className="text-sm font-medium text-muted-foreground">
                              Hosts protegidos:
                            </label>
                            <div className="flex flex-wrap gap-2 mt-1">
                              {tls.hosts.map((host, hostIndex) => (
                                <Badge
                                  key={hostIndex}
                                  variant="secondary"
                                  className="text-green-700 bg-green-100"
                                >
                                  <Shield className="h-3 w-3 mr-1" />
                                  {host}
                                </Badge>
                              ))}
                            </div>
                          </div>
                          {tls.secretName && (
                            <div>
                              <label className="text-sm font-medium text-muted-foreground">
                                Secret:
                              </label>
                              <div className="flex items-center mt-1">
                                <code className="text-sm">
                                  {tls.secretName}
                                </code>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  className="h-6 w-6 ml-2"
                                  onClick={() =>
                                    copyToClipboard(tls.secretName!)
                                  }
                                >
                                  <Copy className="h-3 w-3" />
                                </Button>
                              </div>
                            </div>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>
            )}
          </Tabs>
        </CardContent>
      </Card>

      {/* Endereços de Load Balancer */}
      {ingress.addresses.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <MapPin className="h-5 w-5 mr-2" />
              Endereços do Load Balancer
            </CardTitle>
            <CardDescription>
              {ingress.addresses.length} endereço(s) atribuído(s)
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {ingress.addresses.map((address, index) => (
                <Card key={index} className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <Network className="h-4 w-4 mr-2 text-blue-600" />
                      <span className="font-mono">{address}</span>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6"
                      onClick={() => copyToClipboard(address)}
                    >
                      <Copy className="h-3 w-3" />
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

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

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Excluir Ingress</DialogTitle>
            <DialogDescription>
              Tem certeza que deseja excluir o Ingress{' '}
              <strong>{ingress.name}</strong> do namespace{' '}
              <strong>{ingress.namespace}</strong>?
              <br />
              <br />
              Esta ação não pode ser desfeita e removerá todas as regras de
              roteamento configuradas.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteIngress}
              disabled={deleting}
            >
              {deleting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Excluindo...
                </>
              ) : (
                <>
                  <Trash2 className="h-4 w-4 mr-2" />
                  Excluir Ingress
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
