import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
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 { LogsModal } from '@/components/ui/logs-modal';
import { usePodsInfo, useKubectl, useNamespacesInfo } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Container,
  AlertCircle,
  AlertTriangle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  Clock,
  Calendar,
  Tag,
  Activity,
  Server,
  Zap,
  MoreVertical,
  Info,
  Trash2,
  ArrowUpDown,
  Plus,
  Eye,
  Shield,
  Database,
  Key,
  Copy,
  Pause,
  Play,
  FileText,
  ChevronDown,
} from 'lucide-react';

interface PodInfo {
  metadata: {
    name: string;
    namespace: string;
    creationTimestamp: string;
    labels?: Record<string, string>;
    uid?: string;
  };
  spec: {
    nodeName?: string;
    containers: Array<{
      name: string;
      image: string;
      resources?: {
        requests?: { cpu?: string; memory?: string };
        limits?: { cpu?: string; memory?: string };
      };
    }>;
  };
  status: {
    phase: string;
    podIP?: string;
    startTime?: string;
    containerStatuses?: Array<{
      name: string;
      ready: boolean;
      restartCount: number;
      state?: {
        running?: { startedAt: string };
        waiting?: { reason: string; message?: string };
        terminated?: { reason: string; exitCode: number; finishedAt: string };
      };
    }>;
  };
}

export function PodsPage() {
  const navigate = useNavigate();
  const {
    pods,
    namespaces: podsNamespaces,
    loading,
    error,
    isRefreshing,
    refetch,
    backgroundRefetch,
  } = usePodsInfo();
  const { namespaces: allNamespacesData } = useNamespacesInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();

  const [sortField, setSortField] = useState<string>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [podRefreshInterval, setPodRefreshInterval] = useState(3000); // 3 segundos

  // Modal states
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [logsModalOpen, setLogsModalOpen] = useState(false);
  const [createPodModalOpen, setCreatePodModalOpen] = useState(false);
  const [selectedPod, setSelectedPod] = useState<PodInfo | null>(null);
  const [deleting, setDeleting] = useState(false);

  // Create pod form states
  const [creating, setCreating] = useState(false);
  const [podForm, setPodForm] = useState({
    name: '',
    namespace: selectedNamespace === 'all' ? 'default' : selectedNamespace,
    image: 'nginx:latest',
    port: '80',
    template: 'nginx',
    command: '',
    args: '',
    env: '',
  });

  // Usa todos os namespaces do cluster ao invés de apenas onde há pods
  const namespaces = allNamespacesData.map((ns) => ns.name).sort();

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

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

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

  // Filter and sort pods
  const filteredAndSortedPods = useMemo(() => {
    let filtered = pods;

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

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

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (pod) =>
          pod.metadata.name.toLowerCase().includes(query) ||
          pod.metadata.namespace.toLowerCase().includes(query) ||
          pod.spec.nodeName?.toLowerCase().includes(query),
      );
    }

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

      switch (sortField) {
        case 'name':
          aValue = a.metadata.name;
          bValue = b.metadata.name;
          break;
        case 'namespace':
          aValue = a.metadata.namespace;
          bValue = b.metadata.namespace;
          break;
        case 'status':
          aValue = a.status.phase;
          bValue = b.status.phase;
          break;
        case 'node':
          aValue = a.spec.nodeName || '';
          bValue = b.spec.nodeName || '';
          break;
        case 'age':
          aValue = new Date(a.metadata.creationTimestamp).getTime();
          bValue = new Date(b.metadata.creationTimestamp).getTime();
          break;
        default:
          aValue = a.metadata.name;
          bValue = b.metadata.name;
      }

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

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

  const getPodStatus = (pod: PodInfo) => {
    const { phase } = pod.status;

    switch (phase) {
      case 'Running':
        // Check if all containers are ready
        const allReady =
          pod.status.containerStatuses?.every((c) => c.ready) ?? false;
        return {
          label: allReady ? 'Running' : 'Not Ready',
          color: allReady ? 'text-green-600' : 'text-yellow-600',
          bgColor: allReady ? 'bg-green-100' : 'bg-yellow-100',
          icon: allReady ? CheckCircle : Clock,
        };
      case 'Pending':
        return {
          label: 'Pending',
          color: 'text-yellow-600',
          bgColor: 'bg-yellow-100',
          icon: Clock,
        };
      case 'Succeeded':
        return {
          label: 'Succeeded',
          color: 'text-green-600',
          bgColor: 'bg-green-100',
          icon: CheckCircle,
        };
      case 'Failed':
        return {
          label: 'Failed',
          color: 'text-red-600',
          bgColor: 'bg-red-100',
          icon: XCircle,
        };
      case 'Unknown':
        return {
          label: 'Unknown',
          color: 'text-gray-600',
          bgColor: 'bg-gray-100',
          icon: AlertTriangle,
        };
      default:
        return {
          label: phase,
          color: 'text-gray-600',
          bgColor: 'bg-gray-100',
          icon: AlertCircle,
        };
    }
  };

  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 getRestartCount = (pod: PodInfo) => {
    return (
      pod.status.containerStatuses?.reduce((total, container) => {
        return total + (container.restartCount || 0);
      }, 0) || 0
    );
  };

  const handleDeletePod = async () => {
    if (!selectedPod) return;

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

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

        // Refresh the list
        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Excluir Pod',
          description: result.error || 'Falha ao excluir o pod',
          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);
      setSelectedPod(null);
    }
  };

  const handleDeleteClick = (pod: PodInfo) => {
    setSelectedPod(pod);
    setDeleteModalOpen(true);
  };

  const handleLogsClick = (pod: PodInfo) => {
    setSelectedPod(pod);
    setLogsModalOpen(true);
  };

  const podTemplates = {
    nginx: {
      image: 'nginx:latest',
      port: '80',
      command: '',
      args: '',
      env: '',
    },
    busybox: {
      image: 'busybox:latest',
      port: '',
      command: 'sleep',
      args: '3600',
      env: '',
    },
    ubuntu: {
      image: 'ubuntu:latest',
      port: '',
      command: 'sleep',
      args: 'infinity',
      env: '',
    },
    redis: {
      image: 'redis:latest',
      port: '6379',
      command: '',
      args: '',
      env: '',
    },
    postgres: {
      image: 'postgres:latest',
      port: '5432',
      command: '',
      args: '',
      env: 'POSTGRES_PASSWORD=admin123',
    },
  };

  const handleTemplateChange = (template: string) => {
    const templateConfig = podTemplates[template as keyof typeof podTemplates];
    if (templateConfig) {
      setPodForm((prev) => ({
        ...prev,
        template,
        ...templateConfig,
      }));
    }
  };

  const generatePodName = (template: string) => {
    const timestamp = Date.now().toString(36);
    return `${template}-test-${timestamp}`;
  };

  const handleCreatePod = async () => {
    if (!podForm.name || !podForm.image) {
      showToast({
        title: 'Erro',
        description: 'Nome e imagem são obrigatórios',
        variant: 'destructive',
      });
      return;
    }

    setCreating(true);
    try {
      const envVars = podForm.env
        ? podForm.env
            .split('\n')
            .map((line) => {
              const [name, value] = line.split('=');
              return `        - name: "${name.trim()}"\n          value: "${value ? value.trim() : ''}"`;
            })
            .join('\n')
        : '';

      const yaml = `apiVersion: v1
kind: Pod
metadata:
  name: ${podForm.name}
  namespace: ${podForm.namespace}
  labels:
    app: ${podForm.name}
    created-by: kube-now
spec:
  containers:
  - name: ${podForm.name}
    image: ${podForm.image}${
      podForm.command
        ? `
    command: [${podForm.command
      .split(' ')
      .map((cmd) => `"${cmd}"`)
      .join(', ')}]`
        : ''
    }${
      podForm.args
        ? `
    args: [${podForm.args
      .split(' ')
      .map((arg) => `"${arg}"`)
      .join(', ')}]`
        : ''
    }${
      podForm.port
        ? `
    ports:
    - containerPort: ${podForm.port}`
        : ''
    }${
      envVars
        ? `
    env:
${envVars}`
        : ''
    }
  restartPolicy: Always`;

      const result = await executeCommand(
        `echo '${yaml}' | kubectl apply -f -`,
      );

      if (result.success) {
        showToast({
          title: 'Pod Criado',
          description: `Pod "${podForm.name}" foi criado com sucesso no namespace "${podForm.namespace}"`,
          variant: 'success',
        });

        // Reset form
        setPodForm({
          name: '',
          namespace:
            selectedNamespace === 'all' ? 'default' : selectedNamespace,
          image: 'nginx:latest',
          port: '80',
          template: 'nginx',
          command: '',
          args: '',
          env: '',
        });

        setCreatePodModalOpen(false);
        backgroundRefetch();
      } else {
        showToast({
          title: 'Erro ao Criar Pod',
          description: result.error || 'Falha ao criar o pod',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  const statusStats = useMemo(() => {
    const filtered =
      selectedNamespace === 'all'
        ? pods
        : pods.filter((pod) => pod.metadata.namespace === selectedNamespace);

    return {
      total: filtered.length,
      running: filtered.filter((pod) => pod.status.phase === 'Running').length,
      pending: filtered.filter((pod) => pod.status.phase === 'Pending').length,
      failed: filtered.filter((pod) => pod.status.phase === 'Failed').length,
      succeeded: filtered.filter((pod) => pod.status.phase === 'Succeeded')
        .length,
    };
  }, [pods, 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 pods...</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">
            <Container className="h-8 w-8 mr-3 text-blue-600" />
            Pods
          </h1>
          <p className="text-muted-foreground">
            Gerencie e monitore todos os pods 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 ({podRefreshInterval / 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={() => setPodRefreshInterval(1000)}
                  className={podRefreshInterval === 1000 ? 'bg-green-100' : ''}
                >
                  1 segundo
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setPodRefreshInterval(3000)}
                  className={podRefreshInterval === 3000 ? 'bg-green-100' : ''}
                >
                  3 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setPodRefreshInterval(5000)}
                  className={podRefreshInterval === 5000 ? 'bg-green-100' : ''}
                >
                  5 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setPodRefreshInterval(10000)}
                  className={podRefreshInterval === 10000 ? 'bg-green-100' : ''}
                >
                  10 segundos
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() => setPodRefreshInterval(30000)}
                  className={podRefreshInterval === 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 Pod</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => setCreatePodModalOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Criar Pod
              </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>
            <Container 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">Pods 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">Running</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusStats.running}
            </div>
            <p className="text-xs text-muted-foreground">Em execuçã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">Pending</CardTitle>
            <Clock className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {statusStats.pending}
            </div>
            <p className="text-xs text-muted-foreground">Aguardando</p>
          </CardContent>
        </Card>

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

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

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

            <div className="flex-1 min-w-[200px]">
              <label className="text-sm font-medium mb-2 block">Status</label>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Todos os status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos os status</SelectItem>
                  <SelectItem value="running">Running</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="failed">Failed</SelectItem>
                  <SelectItem value="succeeded">Succeeded</SelectItem>
                </SelectContent>
              </Select>
            </div>

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

      {/* Pods Table */}
      <Card>
        <CardHeader>
          <CardTitle>
            {filteredAndSortedPods.length} pod(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('status')}
                  >
                    Status
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>
                  <Button
                    variant="ghost"
                    className="h-auto p-0 font-semibold"
                    onClick={() => handleSort('node')}
                  >
                    Node
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                  </Button>
                </TableHead>
                <TableHead>Restarts</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>
              {filteredAndSortedPods.map((pod) => {
                const status = getPodStatus(pod);
                const StatusIcon = status.icon;

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

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

      {/* Logs Modal */}
      {selectedPod && (
        <LogsModal
          open={logsModalOpen}
          onOpenChange={setLogsModalOpen}
          podName={selectedPod.metadata.name}
          namespace={selectedPod.metadata.namespace}
          title={`Logs do Pod: ${selectedPod.metadata.name}`}
        />
      )}

      {/* Create Pod Modal */}
      <Dialog open={createPodModalOpen} onOpenChange={setCreatePodModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center">
              <Plus className="h-5 w-5 mr-2" />
              Criar Pod de Teste
            </DialogTitle>
            <DialogDescription>
              Crie rapidamente um pod para testes usando templates
              pré-configurados
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* Template Selection */}
            <div className="space-y-2">
              <Label htmlFor="template">Template</Label>
              <Select
                value={podForm.template}
                onValueChange={(value) => {
                  handleTemplateChange(value);
                  setPodForm((prev) => ({
                    ...prev,
                    name: generatePodName(value),
                  }));
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione um template" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="nginx">
                    <div className="flex items-center">
                      <div className="w-3 h-3 bg-green-500 rounded-full mr-2" />
                      Nginx - Servidor web
                    </div>
                  </SelectItem>
                  <SelectItem value="busybox">
                    <div className="flex items-center">
                      <div className="w-3 h-3 bg-blue-500 rounded-full mr-2" />
                      BusyBox - Utilitários básicos
                    </div>
                  </SelectItem>
                  <SelectItem value="ubuntu">
                    <div className="flex items-center">
                      <div className="w-3 h-3 bg-orange-500 rounded-full mr-2" />
                      Ubuntu - Sistema completo
                    </div>
                  </SelectItem>
                  <SelectItem value="redis">
                    <div className="flex items-center">
                      <div className="w-3 h-3 bg-red-500 rounded-full mr-2" />
                      Redis - Cache/Database
                    </div>
                  </SelectItem>
                  <SelectItem value="postgres">
                    <div className="flex items-center">
                      <div className="w-3 h-3 bg-blue-600 rounded-full mr-2" />
                      PostgreSQL - Database
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid grid-cols-2 gap-4">
              {/* Pod Name */}
              <div className="space-y-2">
                <Label htmlFor="name">Nome do Pod</Label>
                <Input
                  id="name"
                  value={podForm.name}
                  onChange={(e) =>
                    setPodForm((prev) => ({ ...prev, name: e.target.value }))
                  }
                  placeholder="nginx-test-abc123"
                />
              </div>

              {/* Namespace */}
              <div className="space-y-2">
                <Label htmlFor="namespace">Namespace</Label>
                <Select
                  value={podForm.namespace}
                  onValueChange={(value) =>
                    setPodForm((prev) => ({ ...prev, namespace: value }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {namespaces.map((ns) => (
                      <SelectItem key={ns} value={ns}>
                        {ns}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              {/* Image */}
              <div className="space-y-2">
                <Label htmlFor="image">Imagem</Label>
                <Input
                  id="image"
                  value={podForm.image}
                  onChange={(e) =>
                    setPodForm((prev) => ({ ...prev, image: e.target.value }))
                  }
                  placeholder="nginx:latest"
                />
              </div>

              {/* Port */}
              <div className="space-y-2">
                <Label htmlFor="port">Porta (opcional)</Label>
                <Input
                  id="port"
                  value={podForm.port}
                  onChange={(e) =>
                    setPodForm((prev) => ({ ...prev, port: e.target.value }))
                  }
                  placeholder="80"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              {/* Command */}
              <div className="space-y-2">
                <Label htmlFor="command">Comando (opcional)</Label>
                <Input
                  id="command"
                  value={podForm.command}
                  onChange={(e) =>
                    setPodForm((prev) => ({ ...prev, command: e.target.value }))
                  }
                  placeholder="sleep"
                />
              </div>

              {/* Args */}
              <div className="space-y-2">
                <Label htmlFor="args">Argumentos (opcional)</Label>
                <Input
                  id="args"
                  value={podForm.args}
                  onChange={(e) =>
                    setPodForm((prev) => ({ ...prev, args: e.target.value }))
                  }
                  placeholder="3600"
                />
              </div>
            </div>

            {/* Environment Variables */}
            <div className="space-y-2">
              <Label htmlFor="env">Variáveis de Ambiente (opcional)</Label>
              <Textarea
                id="env"
                value={podForm.env}
                onChange={(e) =>
                  setPodForm((prev) => ({ ...prev, env: e.target.value }))
                }
                placeholder="NOME=valor&#10;OUTRA_VAR=outro_valor"
                rows={3}
                className="resize-none"
              />
              <p className="text-xs text-muted-foreground">
                Uma variável por linha no formato: NOME=valor
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setCreatePodModalOpen(false)}
              disabled={creating}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleCreatePod}
              disabled={creating || !podForm.name || !podForm.image}
            >
              {creating ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Criando...
                </>
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  Criar Pod
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
