import React, { useState } 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 { Input } from '@/components/ui/input';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { useNamespacesInfo, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  FolderOpen,
  AlertCircle,
  RefreshCw,
  MoreVertical,
  Plus,
  Trash2,
  Info,
  Tag,
  Calendar,
  Shield,
  Archive,
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

export function NamespacesPage() {
  const navigate = useNavigate();
  const { namespaces, loading, error, refetch } = useNamespacesInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [newNamespaceName, setNewNamespaceName] = useState('');
  const [nameError, setNameError] = useState('');
  const [creating, setCreating] = useState(false);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [namespaceToDelete, setNamespaceToDelete] = useState<string | null>(
    null,
  );
  const [deleting, setDeleting] = useState(false);

  const validateNamespaceName = (name: string): string => {
    if (!name) {
      return 'Nome do namespace é obrigatório';
    }
    if (name.length < 2) {
      return 'Nome deve ter pelo menos 2 caracteres';
    }
    if (name.length > 63) {
      return 'Nome deve ter no máximo 63 caracteres';
    }
    if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(name)) {
      return 'Nome deve conter apenas letras minúsculas, números e hífens. Deve começar e terminar com caractere alfanumérico';
    }
    if (namespaces.some((ns) => ns.name === name)) {
      return 'Namespace com este nome já existe';
    }
    return '';
  };

  const handleCreateNamespace = async () => {
    const error = validateNamespaceName(newNamespaceName);
    if (error) {
      setNameError(error);
      return;
    }

    setCreating(true);
    try {
      const command = `kubectl create namespace ${newNamespaceName}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Namespace Criado',
          description: `O namespace "${newNamespaceName}" foi criado com sucesso`,
          variant: 'success',
        });
        setCreateModalOpen(false);
        setNewNamespaceName('');
        setNameError('');
        await refetch();
      } else {
        setNameError(result.error || 'Falha ao criar namespace');
        showToast({
          title: 'Erro ao Criar Namespace',
          description: result.error || 'Falha ao criar namespace',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      setNameError(errorMsg);
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  const handleDeleteClick = (namespaceName: string) => {
    setNamespaceToDelete(namespaceName);
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!namespaceToDelete) return;

    setDeleting(true);
    try {
      const command = `kubectl delete namespace ${namespaceToDelete}`;
      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'Namespace Deletado',
          description: `O namespace "${namespaceToDelete}" foi deletado com sucesso`,
          variant: 'success',
        });
        setDeleteModalOpen(false);
        setNamespaceToDelete(null);
        await refetch();
      } else {
        showToast({
          title: 'Erro ao Deletar Namespace',
          description: result.error || 'Falha ao deletar namespace',
          variant: 'destructive',
        });
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setDeleting(false);
    }
  };

  const handleNamespaceAction = async (
    namespaceName: string,
    action: string,
  ) => {
    setActionLoading(namespaceName);
    try {
      let command = '';
      switch (action) {
        case 'describe':
          command = `kubectl describe namespace ${namespaceName}`;
          break;
        default:
          return;
      }

      const result = await executeCommand(command);
      if (result.success) {
        console.log(`${action} executed successfully:`, result.data);
      } else {
        console.error(`${action} failed:`, result.error);
        showToast({
          title: 'Erro na Operação',
          description: result.error || `Falha ao executar ${action}`,
          variant: 'destructive',
        });
      }
    } catch (err) {
      console.error(`Error executing ${action}:`, err);
      showToast({
        title: 'Erro',
        description: `Erro inesperado ao executar ${action}`,
        variant: 'destructive',
      });
    } finally {
      setActionLoading(null);
    }
  };

  const getNamespaceStatus = (status: string) => {
    switch (status) {
      case 'Active':
        return (
          <Badge variant="default" className="bg-green-500">
            Ativo
          </Badge>
        );
      case 'Terminating':
        return <Badge variant="destructive">Terminando</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const getNamespaceAge = (creationTimestamp: string) => {
    const creationTime = new Date(creationTimestamp);
    const now = new Date();
    const diffMs = now.getTime() - creationTime.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      return `${diffHours}h`;
    }
    return `${diffDays} dias`;
  };

  const isSystemNamespace = (namespaceName: string) => {
    const systemNamespaces = [
      'kube-system',
      'kube-public',
      'kube-node-lease',
      'default',
    ];
    return systemNamespaces.includes(namespaceName);
  };

  const getNamespaceLabels = (labels: Record<string, string>) => {
    const labelKeys = Object.keys(labels);
    if (labelKeys.length === 0) return '-';

    if (labelKeys.length <= 2) {
      return labelKeys.map((key) => `${key}=${labels[key]}`).join(', ');
    }

    return `${labelKeys.length} labels`;
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">Namespaces</h1>
            <p className="text-muted-foreground">
              Gerenciar namespaces do cluster Kubernetes
            </p>
          </div>
        </div>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin" />
          <span className="ml-2">Carregando namespaces...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">Namespaces</h1>
            <p className="text-muted-foreground">
              Gerenciar namespaces do cluster Kubernetes
            </p>
          </div>
        </div>
        <Card className="border-red-200">
          <CardHeader>
            <CardTitle className="text-red-600 flex items-center">
              <AlertCircle className="h-5 w-5 mr-2" />
              Erro ao carregar namespaces
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-500 mb-4">{error}</p>
            <Button onClick={refetch} variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar novamente
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const totalNamespaces = namespaces.length;
  const activeNamespaces = namespaces.filter(
    (ns) => ns.status === 'Active',
  ).length;
  const systemNamespaces = namespaces.filter((ns) =>
    isSystemNamespace(ns.name),
  ).length;
  const userNamespaces = totalNamespaces - systemNamespaces;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Namespaces</h1>
          <p className="text-muted-foreground">
            Gerenciar {totalNamespaces} namespace(s) do cluster Kubernetes
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Button onClick={refetch} variant="outline">
            <RefreshCw className="h-4 w-4 mr-2" />
            Atualizar
          </Button>
          <Dialog open={createModalOpen} onOpenChange={setCreateModalOpen}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Criar Namespace
              </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[425px]">
              <DialogHeader>
                <DialogTitle>Criar Novo Namespace</DialogTitle>
                <DialogDescription>
                  Digite o nome do namespace que deseja criar. O nome deve
                  seguir as convenções do Kubernetes.
                </DialogDescription>
              </DialogHeader>
              <div className="grid gap-4 py-4">
                <div className="grid gap-2">
                  <label
                    htmlFor="namespace-name"
                    className="text-sm font-medium"
                  >
                    Nome do Namespace
                  </label>
                  <Input
                    id="namespace-name"
                    placeholder="ex: meu-namespace"
                    value={newNamespaceName}
                    onChange={(e) => {
                      setNewNamespaceName(e.target.value);
                      setNameError('');
                    }}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter' && !nameError && newNamespaceName) {
                        handleCreateNamespace();
                      }
                    }}
                    disabled={creating}
                  />
                  {nameError && (
                    <p className="text-sm text-red-500">{nameError}</p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    Use apenas letras minúsculas, números e hífens. Deve começar
                    e terminar com um caractere alfanumérico.
                  </p>
                </div>
              </div>
              <DialogFooter>
                <Button
                  variant="outline"
                  onClick={() => {
                    setCreateModalOpen(false);
                    setNewNamespaceName('');
                    setNameError('');
                  }}
                  disabled={creating}
                >
                  Cancelar
                </Button>
                <Button
                  onClick={handleCreateNamespace}
                  disabled={creating || !newNamespaceName || !!nameError}
                >
                  {creating && (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  )}
                  {creating ? 'Criando...' : 'Criar Namespace'}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      <Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle className="text-red-600">
              Confirmar Exclusão
            </DialogTitle>
            <DialogDescription>
              Tem certeza que deseja deletar o namespace{' '}
              <strong>"{namespaceToDelete}"</strong>?
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <div className="flex items-start">
                <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" />
                <div className="text-sm text-yellow-800">
                  <p className="font-medium mb-1">⚠️ Atenção:</p>
                  <p>Esta ação é irreversível e irá deletar:</p>
                  <ul className="list-disc list-inside mt-2 space-y-1">
                    <li>O namespace e todos os seus recursos</li>
                    <li>Pods, Services, ConfigMaps, Secrets</li>
                    <li>Todos os dados dentro do namespace</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setDeleteModalOpen(false);
                setNamespaceToDelete(null);
              }}
              disabled={deleting}
            >
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmDelete}
              disabled={deleting}
            >
              {deleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              {deleting ? 'Deletando...' : 'Sim, Deletar'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total</CardTitle>
            <FolderOpen className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalNamespaces}</div>
            <p className="text-xs text-muted-foreground">
              Namespaces 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">Ativos</CardTitle>
            <Shield className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeNamespaces}</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">Sistema</CardTitle>
            <Archive className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{systemNamespaces}</div>
            <p className="text-xs text-muted-foreground">
              Namespaces do sistema
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Usuário</CardTitle>
            <Tag className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{userNamespaces}</div>
            <p className="text-xs text-muted-foreground">
              Criados pelo usuário
            </p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Lista de Namespaces</CardTitle>
          <CardDescription>
            Todos os namespaces do cluster com informações detalhadas
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Status</TableHead>
                <TableHead>Nome</TableHead>
                <TableHead>Tipo</TableHead>
                <TableHead>Labels</TableHead>
                <TableHead className="w-24">Idade</TableHead>
                <TableHead>Data de Criação</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {namespaces.map((namespace, index) => (
                <TableRow key={index} className="h-8">
                  <TableCell>{getNamespaceStatus(namespace.status)}</TableCell>
                  <TableCell className="font-medium">
                    <div
                      className="flex items-center space-x-2 cursor-pointer hover:text-blue-600 transition-colors"
                      onClick={() =>
                        navigate(`/cluster/namespaces/${namespace.name}`)
                      }
                      title="Clique para ver detalhes"
                    >
                      <FolderOpen
                        className={`h-4 w-4 ${isSystemNamespace(namespace.name) ? 'text-purple-600' : 'text-blue-600'}`}
                      />
                      <span className="hover:underline">{namespace.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    {isSystemNamespace(namespace.name) ? (
                      <Badge variant="secondary">Sistema</Badge>
                    ) : (
                      <Badge variant="outline">Usuário</Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-sm max-w-xs truncate">
                    {getNamespaceLabels(namespace.labels)}
                  </TableCell>
                  <TableCell className="text-sm">
                    {getNamespaceAge(namespace.creationTimestamp)}
                  </TableCell>
                  <TableCell className="text-sm">
                    <div className="flex items-center space-x-1">
                      <Calendar className="h-3 w-3 text-muted-foreground" />
                      <span>
                        {new Date(
                          namespace.creationTimestamp,
                        ).toLocaleDateString('pt-BR')}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end space-x-2">
                      {actionLoading === namespace.name && (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      )}
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuLabel>
                            Ações do Namespace
                          </DropdownMenuLabel>
                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() =>
                              navigate(`/cluster/namespaces/${namespace.name}`)
                            }
                            disabled={actionLoading === namespace.name}
                          >
                            <Info className="h-4 w-4 mr-2" />
                            Visualizar
                          </DropdownMenuItem>

                          {!isSystemNamespace(namespace.name) && (
                            <>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() =>
                                  handleDeleteClick(namespace.name)
                                }
                                disabled={actionLoading === namespace.name}
                                className="text-red-600"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Deletar
                              </DropdownMenuItem>
                            </>
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
