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 { useNodesInfo, useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  Server,
  AlertCircle,
  RefreshCw,
  MoreVertical,
  Power,
  Shield,
  ShieldOff,
  Trash2,
  Info,
  Cpu,
  Database,
  HardDrive,
  Globe,
  Monitor,
} 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 NodesPage() {
  const navigate = useNavigate();
  const { nodes, loading, error, refetch } = useNodesInfo();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const handleNodeAction = async (nodeName: string, action: string) => {
    setActionLoading(nodeName);
    try {
      let command = '';
      switch (action) {
        case 'cordon':
          command = `kubectl cordon ${nodeName}`;
          break;
        case 'uncordon':
          command = `kubectl uncordon ${nodeName}`;
          break;
        case 'drain':
          command = `kubectl drain ${nodeName} --ignore-daemonsets --delete-emptydir-data --force`;
          break;
        case 'describe':
          command = `kubectl describe node ${nodeName}`;
          break;
        default:
          return;
      }

      const result = await executeCommand(command);
      if (result.success) {
        console.log(`${action} executed successfully:`, result.data);
        if (action !== 'describe') {
          await refetch(); // Refresh the nodes list
        }
      } else {
        console.error(`${action} failed:`, result.error);
      }
    } catch (err) {
      console.error(`Error executing ${action}:`, err);
    } finally {
      setActionLoading(null);
    }
  };

  const getNodeStatus = (node: any) => {
    const conditions = node.status?.conditions || [];

    // Verificar Memory Pressure
    const memoryPressure = conditions.find(
      (c: any) => c.type === 'MemoryPressure',
    );
    if (memoryPressure?.status === 'True') {
      return 'MemoryPressure';
    }

    // Verificar Disk Pressure
    const diskPressure = conditions.find((c: any) => c.type === 'DiskPressure');
    if (diskPressure?.status === 'True') {
      return 'DiskPressure';
    }

    // Verificar PID Pressure
    const pidPressure = conditions.find((c: any) => c.type === 'PIDPressure');
    if (pidPressure?.status === 'True') {
      return 'PIDPressure';
    }

    // Verificar Network Unavailable
    const networkUnavailable = conditions.find(
      (c: any) => c.type === 'NetworkUnavailable',
    );
    if (networkUnavailable?.status === 'True') {
      return 'NetworkUnavailable';
    }

    // Verificar se está cordoned (scheduling disabled)
    if (node.spec?.unschedulable) {
      return 'SchedulingDisabled';
    }

    // Verificar Ready status
    const readyCondition = conditions.find((c: any) => c.type === 'Ready');
    if (readyCondition?.status === 'True') {
      return 'Ready';
    }

    return 'NotReady';
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'Ready':
        return (
          <Badge variant="default" className="bg-green-500">
            Ready
          </Badge>
        );
      case 'NotReady':
        return <Badge variant="destructive">Not Ready</Badge>;
      case 'SchedulingDisabled':
        return <Badge variant="secondary">Cordoned</Badge>;
      case 'MemoryPressure':
        return <Badge variant="destructive">Memory Pressure</Badge>;
      case 'DiskPressure':
        return <Badge variant="destructive">Disk Pressure</Badge>;
      case 'PIDPressure':
        return <Badge variant="destructive">PID Pressure</Badge>;
      case 'NetworkUnavailable':
        return <Badge variant="destructive">Network Issue</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const formatMemory = (memory: string) => {
    if (memory.endsWith('Ki')) {
      const value = parseInt(memory.replace('Ki', ''));
      return `${Math.round(value / 1024 / 1024)} GB`;
    }
    return memory;
  };

  const formatCpu = (cpu: string) => {
    if (cpu.endsWith('m')) {
      const value = parseInt(cpu.replace('m', ''));
      return `${value / 1000} cores`;
    }
    return `${cpu} cores`;
  };

  const formatStorage = (storage: string) => {
    if (storage.endsWith('Ki')) {
      const value = parseInt(storage.replace('Ki', ''));
      return `${Math.round(value / 1024 / 1024)} GB`;
    }
    return storage;
  };

  const getNodeRoles = (node: any) => {
    const labels = node.labels || {};
    const roles = [];

    if (
      labels['node-role.kubernetes.io/control-plane'] ||
      labels['node-role.kubernetes.io/master']
    ) {
      roles.push('control-plane');
    }
    if (labels['node-role.kubernetes.io/worker']) {
      roles.push('worker');
    }

    return roles.length > 0 ? roles.join(', ') : 'worker';
  };

  const getNodeAge = (node: any) => {
    const creationTime = new Date(node.metadata?.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`;
    }
    if (diffDays < 30) {
      return `${diffDays}d`;
    }
    const diffMonths = Math.floor(diffDays / 30);
    return `${diffMonths}mo`;
  };

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      showToast({
        title: 'IP Copiado!',
        description: `${text} foi copiado para a área de transferência`,
        variant: 'success',
      });
    } catch (err) {
      console.error('Erro ao copiar para clipboard:', err);
      showToast({
        title: 'Erro',
        description: 'Não foi possível copiar o IP',
        variant: 'destructive',
      });
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin" />
        <span className="ml-2">Carregando nodes...</span>
      </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">Nodes</h1>
            <p className="text-muted-foreground">
              Gerenciar nodes 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 nodes
            </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>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Nodes</h1>
          <p className="text-muted-foreground">
            Gerenciar {nodes.length} node(s) do cluster Kubernetes
          </p>
        </div>
        <Button onClick={refetch} variant="outline">
          <RefreshCw className="h-4 w-4 mr-2" />
          Atualizar
        </Button>
      </div>

      {/* Nodes Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Nodes</CardTitle>
            <Server className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{nodes.length}</div>
            <p className="text-xs text-muted-foreground">Nodes 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">Total CPU</CardTitle>
            <Cpu className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-lg font-bold">
              {nodes.reduce((total, node) => {
                const cpu = parseInt(node.capacity?.cpu || '0');
                return total + cpu;
              }, 0)}{' '}
              cores
            </div>
            <p className="text-xs text-muted-foreground">Capacidade total</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Memory</CardTitle>
            <Monitor className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            <div className="text-lg font-bold">
              {Math.round(
                nodes.reduce((total, node) => {
                  const memory = node.capacity?.memory || '0Ki';
                  const value = parseInt(memory.replace('Ki', ''));
                  return total + value / 1024 / 1024;
                }, 0),
              )}{' '}
              GB
            </div>
            <p className="text-xs text-muted-foreground">Capacidade total</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Pods</CardTitle>
            <HardDrive className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-lg font-bold">
              {nodes.reduce((total, node) => {
                const pods = parseInt(node.capacity?.pods || '0');
                return total + pods;
              }, 0)}
            </div>
            <p className="text-xs text-muted-foreground">Capacidade de pods</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Arquiteturas</CardTitle>
            <Info className="h-4 w-4 text-cyan-600" />
          </CardHeader>
          <CardContent>
            <div className="text-sm font-bold">
              {[...new Set(nodes.map((n) => n.architecture))].join(', ')}
            </div>
            <p className="text-xs text-muted-foreground">Tipos disponíveis</p>
          </CardContent>
        </Card>
      </div>

      {/* Nodes Table */}
      <Card>
        <CardHeader>
          <CardTitle>Lista de Nodes</CardTitle>
          <CardDescription>
            Todos os nodes do cluster com informações detalhadas
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Status</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>Roles</TableHead>
                <TableHead>Version</TableHead>
                <TableHead>IP (Internal/External)</TableHead>
                <TableHead>OS</TableHead>
                <TableHead>CPU</TableHead>
                <TableHead>RAM</TableHead>
                <TableHead>PODS</TableHead>
                <TableHead>Age</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {nodes.map((node, index) => (
                <TableRow key={index}>
                  <TableCell>{getStatusBadge(getNodeStatus(node))}</TableCell>
                  <TableCell className="font-medium">
                    <div
                      className="flex items-center space-x-2 cursor-pointer hover:text-blue-600 transition-colors"
                      onClick={() => navigate(`/cluster/nodes/${node.name}`)}
                      title="Clique para ver detalhes"
                    >
                      <Server className="h-4 w-4 text-blue-600" />
                      <span className="hover:underline">{node.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>{getNodeRoles(node)}</TableCell>
                  <TableCell className="text-sm">
                    {node.kubeletVersion}
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div className="flex items-center space-x-1">
                        <Globe
                          className="h-3 w-3 cursor-pointer hover:text-blue-500 transition-colors"
                          onClick={() =>
                            copyToClipboard(node.addresses?.internalIP || '')
                          }
                          title="Clique para copiar IP interno"
                        />
                        <span>{node.addresses?.internalIP || 'N/A'}</span>
                      </div>
                      {node.addresses?.externalIP && (
                        <div className="text-muted-foreground text-xs flex items-center space-x-1">
                          <Globe
                            className="h-3 w-3 cursor-pointer hover:text-blue-500 transition-colors"
                            onClick={() =>
                              copyToClipboard(node.addresses.externalIP)
                            }
                            title="Clique para copiar IP externo"
                          />
                          <span>Ext: {node.addresses.externalIP}</span>
                        </div>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{node.operatingSystem}</div>
                      <div className="text-xs text-muted-foreground">
                        {node.architecture}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Cpu className="h-3 w-3 text-green-600" />
                      <span className="text-sm">
                        {formatCpu(node.capacity?.cpu || '0')}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Monitor className="h-3 w-3 text-purple-600" />
                      <span className="text-sm">
                        {formatMemory(node.capacity?.memory || '0Ki')}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <HardDrive className="h-3 w-3 text-orange-600" />
                      <span className="text-sm">
                        {node.capacity?.pods || '0'}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">{getNodeAge(node)}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end space-x-2">
                      {actionLoading === node.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 Node</DropdownMenuLabel>
                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() =>
                              handleNodeAction(node.name, 'describe')
                            }
                            disabled={actionLoading === node.name}
                          >
                            <Info className="h-4 w-4 mr-2" />
                            Describir Node
                          </DropdownMenuItem>

                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() =>
                              handleNodeAction(node.name, 'cordon')
                            }
                            disabled={actionLoading === node.name}
                          >
                            <ShieldOff className="h-4 w-4 mr-2" />
                            Cordon
                          </DropdownMenuItem>

                          <DropdownMenuItem
                            onClick={() =>
                              handleNodeAction(node.name, 'uncordon')
                            }
                            disabled={actionLoading === node.name}
                          >
                            <Shield className="h-4 w-4 mr-2" />
                            Uncordon
                          </DropdownMenuItem>

                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() => handleNodeAction(node.name, 'drain')}
                            disabled={actionLoading === node.name}
                            className="text-orange-600"
                          >
                            <Power className="h-4 w-4 mr-2" />
                            Drain Node
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
