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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { YamlEditor } from '@/components/ui/yaml-editor';
import { useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import {
  Loader2,
  ArrowLeft,
  RefreshCw,
  Activity,
  TrendingUp,
  TrendingDown,
  Minus,
  AlertCircle,
  Target,
  Gauge,
  Calendar,
  FileText,
  CheckCircle,
  XCircle,
  Info,
  Eye,
} from 'lucide-react';

interface HPADetails {
  name: string;
  namespace: string;
  targetKind: string;
  targetName: string;
  minReplicas: number;
  maxReplicas: number;
  currentReplicas: number;
  desiredReplicas: number;
  metrics: Array<{
    type: string;
    name: string;
    target: number;
    current?: number;
  }>;
  conditions: Array<{
    type: string;
    status: string;
    reason: string;
    message: string;
    lastTransitionTime: string;
  }>;
  creationTimestamp: string;
}

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

  const [hpaDetails, setHpaDetails] = useState<HPADetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [events, setEvents] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState('overview');
  const [yamlDrawerOpen, setYamlDrawerOpen] = useState(false);

  const fetchHPADetails = async () => {
    if (!hpaName || !namespaceName) return;

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

      // Buscar HPA
      const hpaCommand = `kubectl get hpa ${hpaName} -n ${namespaceName} -o json`;
      const hpaResult = await executeCommand(hpaCommand);

      if (!hpaResult.success || !hpaResult.data) {
        throw new Error(hpaResult.error || 'Erro ao buscar HPA');
      }

      const hpaData = JSON.parse(hpaResult.data);

      // Buscar eventos
      const eventsCommand = `kubectl get events -n ${namespaceName} --field-selector involvedObject.name=${hpaName},involvedObject.kind=HorizontalPodAutoscaler -o json`;
      const eventsResult = await executeCommand(eventsCommand);

      const eventsData = eventsResult.success && eventsResult.data
        ? JSON.parse(eventsResult.data).items
        : [];

      // Processar métricas
      const metrics = hpaData.spec.metrics?.map((m: any) => {
        if (m.type === 'Resource') {
          const current = hpaData.status.currentMetrics?.find(
            (cm: any) => cm.resource?.name === m.resource.name
          );

          return {
            type: 'Resource',
            name: m.resource.name,
            target: m.resource.target.averageUtilization || m.resource.target.averageValue,
            current: current?.resource?.current?.averageUtilization,
          };
        }
        return {
          type: m.type,
          name: m.type,
          target: 0,
        };
      }) || [];

      const details: HPADetails = {
        name: hpaData.metadata.name,
        namespace: hpaData.metadata.namespace,
        targetKind: hpaData.spec.scaleTargetRef.kind,
        targetName: hpaData.spec.scaleTargetRef.name,
        minReplicas: hpaData.spec.minReplicas || 1,
        maxReplicas: hpaData.spec.maxReplicas,
        currentReplicas: hpaData.status.currentReplicas || 0,
        desiredReplicas: hpaData.status.desiredReplicas || 0,
        metrics,
        conditions: hpaData.status.conditions || [],
        creationTimestamp: hpaData.metadata.creationTimestamp,
      };

      setHpaDetails(details);
      setEvents(eventsData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erro desconhecido');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchHPADetails();
  }, [hpaName, namespaceName]);

  const getScalingStatus = () => {
    if (!hpaDetails) return null;

    if (hpaDetails.currentReplicas < hpaDetails.desiredReplicas) {
      return (
        <Badge className="bg-blue-500 hover:bg-blue-600 text-white">
          <TrendingUp className="h-3 w-3 mr-1" />
          Scaling Up
        </Badge>
      );
    } else if (hpaDetails.currentReplicas > hpaDetails.desiredReplicas) {
      return (
        <Badge className="bg-orange-500 hover:bg-orange-600 text-white">
          <TrendingDown className="h-3 w-3 mr-1" />
          Scaling Down
        </Badge>
      );
    } else {
      return (
        <Badge className="bg-green-500 hover:bg-green-600 text-white">
          <Minus className="h-3 w-3 mr-1" />
          Stable
        </Badge>
      );
    }
  };

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

    if (diffDays > 0) return `${diffDays}d`;
    if (diffHours > 0) return `${diffHours}h`;
    return `${diffMinutes}m`;
  };

  const formatTimestamp = (timestamp: string) => {
    return new Date(timestamp).toLocaleString('pt-BR');
  };

  const handleYamlView = () => {
    setYamlDrawerOpen(true);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <Loader2 className="h-8 w-8 animate-spin" />
        <span className="ml-2">Carregando detalhes do HPA...</span>
      </div>
    );
  }

  if (error || !hpaDetails) {
    return (
      <div className="space-y-6 p-6">
        <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">Erro</h1>
          </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 HPA
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-500 mb-4">{error || 'HPA não encontrado'}</p>
            <Button onClick={() => navigate('/workloads/hpa')} variant="outline">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Voltar para lista
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  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">
              <Activity className="h-8 w-8 mr-3 text-blue-600" />
              {hpaDetails.name}
            </h1>
            <p className="text-muted-foreground">
              Horizontal Pod Autoscaler em {hpaDetails.namespace}
            </p>
          </div>
        </div>
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="sm" onClick={fetchHPADetails}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Atualizar
          </Button>
        </div>
      </div>

      {/* HPA Configuration Card */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center">
              <Activity className="h-5 w-5 mr-2" />
              Configuração do HPA
            </CardTitle>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" onClick={handleYamlView}>
                <Eye className="h-4 w-4 mr-2" />
                YAML
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Tabs
            value={activeTab}
            onValueChange={setActiveTab}
            className="w-full"
          >
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="overview">Visão Geral</TabsTrigger>
              <TabsTrigger value="metrics">Métricas</TabsTrigger>
              <TabsTrigger value="events">Eventos</TabsTrigger>
            </TabsList>

            <TabsContent value="overview" className="mt-6">
              {/* Status Cards */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Status</CardTitle>
                    <Activity className="h-4 w-4 text-blue-600" />
                  </CardHeader>
                  <CardContent>{getScalingStatus()}</CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">
                      Réplicas Atuais
                    </CardTitle>
                    <Gauge className="h-4 w-4 text-green-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{hpaDetails.currentReplicas}</div>
                    <p className="text-xs text-muted-foreground">
                      Desejadas: {hpaDetails.desiredReplicas}
                    </p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Range</CardTitle>
                    <TrendingUp className="h-4 w-4 text-orange-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {hpaDetails.minReplicas} - {hpaDetails.maxReplicas}
                    </div>
                    <p className="text-xs text-muted-foreground">Min / Max réplicas</p>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Idade</CardTitle>
                    <Calendar className="h-4 w-4 text-purple-600" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {getAge(hpaDetails.creationTimestamp)}
                    </div>
                    <p className="text-xs text-muted-foreground">Tempo ativo</p>
                  </CardContent>
                </Card>
              </div>

              {/* Informações Detalhadas em Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-12">
                {/* Coluna 1: Target */}
                <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                  <h3 className="text-sm font-semibold mb-4 text-muted-foreground uppercase">
                    Target de Escalação
                  </h3>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Tipo:
                    </span>
                    <Badge variant="outline">{hpaDetails.targetKind}</Badge>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Nome:
                    </span>
                    <span className="text-sm font-semibold text-right ml-4">
                      {hpaDetails.targetName}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Namespace:
                    </span>
                    <Badge variant="outline">{hpaDetails.namespace}</Badge>
                  </div>
                </div>

                {/* Coluna 2: Réplicas */}
                <div className="space-y-5 pr-6 border-r border-gray-100 last:border-r-0">
                  <h3 className="text-sm font-semibold mb-4 text-muted-foreground uppercase">
                    Configuração de Réplicas
                  </h3>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Mínimo:
                    </span>
                    <span className="text-sm font-semibold text-right ml-4">
                      {hpaDetails.minReplicas} réplicas
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Máximo:
                    </span>
                    <span className="text-sm font-semibold text-right ml-4">
                      {hpaDetails.maxReplicas} réplicas
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Atual:
                    </span>
                    <span className="text-sm font-bold text-blue-600 text-right ml-4">
                      {hpaDetails.currentReplicas} réplicas
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Desejado:
                    </span>
                    <span className="text-sm font-bold text-green-600 text-right ml-4">
                      {hpaDetails.desiredReplicas} réplicas
                    </span>
                  </div>
                </div>

                {/* Coluna 3: Informações Gerais */}
                <div className="space-y-5">
                  <h3 className="text-sm font-semibold mb-4 text-muted-foreground uppercase">
                    Informações Gerais
                  </h3>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Criado em:
                    </span>
                    <span className="text-sm font-semibold text-right ml-4">
                      {formatTimestamp(hpaDetails.creationTimestamp)}
                    </span>
                  </div>
                  <div className="flex justify-between items-start min-h-[20px]">
                    <span className="text-sm text-muted-foreground font-medium">
                      Idade:
                    </span>
                    <span className="text-sm font-semibold text-right ml-4">
                      {getAge(hpaDetails.creationTimestamp)}
                    </span>
                  </div>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="metrics" className="mt-6">
              <div className="mb-4">
                <h3 className="text-sm font-semibold flex items-center text-muted-foreground">
                  <Gauge className="h-4 w-4 mr-2" />
                  Métricas utilizadas para decisões de escalação
                </h3>
              </div>
              <div className="space-y-4">
                {hpaDetails.metrics.map((metric, index) => {
                  // Detectar se é métrica de memória
                  const isMemory = metric.name.toLowerCase() === 'memory';

                  // Para memória, vamos simular valores em Mi baseado nas porcentagens
                  // Assumindo request de 100Mi como base (em produção, buscaríamos o valor real)
                  const memoryRequestBase = 100; // Mi

                  let currentValue, targetValue, maxValue, unit;

                  if (isMemory) {
                    // Converter porcentagens para valores de memória
                    targetValue = (metric.target / 100) * memoryRequestBase;
                    currentValue = (metric.current || 0) / 100 * memoryRequestBase;
                    maxValue = Math.max(
                      memoryRequestBase * 2, // 200Mi
                      currentValue * 1.2,
                      targetValue * 3
                    );
                    unit = 'Mi';
                  } else {
                    // Para CPU e outras métricas, manter porcentagem
                    currentValue = metric.current || 0;
                    targetValue = metric.target;
                    maxValue = Math.max(
                      200,
                      currentValue * 1.2,
                      targetValue * 2
                    );
                    unit = '%';
                  }

                  // Calcular posições na barra
                  const currentPosition = (currentValue / maxValue) * 100;
                  const targetPosition = (targetValue / maxValue) * 100;

                  return (
                    <Card key={index} className="p-6">
                      <div className="flex items-center justify-between mb-4">
                        <h4 className="font-semibold text-lg">
                          {metric.name.toUpperCase()}
                        </h4>
                        <Badge variant="outline">{metric.type}</Badge>
                      </div>

                      {/* Valores */}
                      <div className="grid grid-cols-2 gap-4 mb-4">
                        <div>
                          <span className="text-xs text-muted-foreground">Target (Esperado)</span>
                          <div className="text-2xl font-bold text-blue-600">
                            {targetValue.toFixed(0)}{unit}
                          </div>
                        </div>
                        {currentValue !== undefined && (
                          <div>
                            <span className="text-xs text-muted-foreground">Atual (Usando agora)</span>
                            <div
                              className={`text-2xl font-bold ${
                                currentValue > targetValue
                                  ? 'text-red-600'
                                  : 'text-green-600'
                              }`}
                            >
                              {currentValue.toFixed(0)}{unit}
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Explicação para memória */}
                      {isMemory && (
                        <div className="mb-3 p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                          <p className="text-xs text-muted-foreground">
                            💡 <strong>O que isso significa:</strong> Cada pod está usando{' '}
                            <strong className="text-blue-600">{currentValue.toFixed(0)}Mi</strong> de memória,
                            mas o esperado é <strong className="text-blue-600">{targetValue.toFixed(0)}Mi</strong>.
                            {currentValue > targetValue ? (
                              <span className="text-red-600">
                                {' '}Está {((currentValue / targetValue - 1) * 100).toFixed(0)}% acima do esperado,
                                então o HPA vai criar mais réplicas.
                              </span>
                            ) : (
                              <span className="text-green-600"> Está dentro do esperado.</span>
                            )}
                          </p>
                        </div>
                      )}

                      {/* Barra de progresso com escala */}
                      <div className="relative">
                        {/* Labels da escala */}
                        <div className="flex justify-between text-xs text-muted-foreground mb-1">
                          <span>0{unit}</span>
                          <span>{(maxValue / 2).toFixed(0)}{unit}</span>
                          <span>{maxValue.toFixed(0)}{unit}</span>
                        </div>

                        {/* Barra container */}
                        <div className="relative w-full bg-gray-200 rounded-full h-8">
                          {/* Barra de progresso atual */}
                          <div
                            className={`h-8 rounded-full transition-all duration-300 ${
                              currentValue > targetValue
                                ? 'bg-red-500'
                                : 'bg-green-500'
                            }`}
                            style={{
                              width: `${Math.min(currentPosition, 100)}%`,
                            }}
                          >
                            {currentValue > 0 && (
                              <div className="flex items-center justify-end h-full pr-2">
                                <span className="text-xs font-bold text-white">
                                  {currentValue.toFixed(0)}{unit}
                                </span>
                              </div>
                            )}
                          </div>

                          {/* Linha do target */}
                          <div
                            className="absolute top-0 bottom-0 w-0.5 bg-blue-600"
                            style={{
                              left: `${targetPosition}%`,
                            }}
                          >
                            <div className="absolute -top-6 left-1/2 -translate-x-1/2 whitespace-nowrap">
                              <div className="bg-blue-600 text-white text-xs px-2 py-0.5 rounded">
                                Target: {targetValue.toFixed(0)}{unit}
                              </div>
                            </div>
                          </div>
                        </div>

                        {/* Status */}
                        <div className="mt-2 text-center">
                          {currentValue > targetValue ? (
                            <span className="text-xs text-red-600 font-medium">
                              ⚠️ Acima do target - HPA vai escalar para mais réplicas
                            </span>
                          ) : currentValue < targetValue * 0.8 ? (
                            <span className="text-xs text-orange-600 font-medium">
                              ⬇️ Abaixo do target - HPA pode reduzir réplicas
                            </span>
                          ) : (
                            <span className="text-xs text-green-600 font-medium">
                              ✓ Dentro do esperado
                            </span>
                          )}
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            </TabsContent>

            <TabsContent value="events" className="mt-6">
              <div className="mb-4">
                <h3 className="text-sm font-semibold flex items-center text-muted-foreground">
                  <Activity className="h-4 w-4 mr-2" />
                  Eventos recentes relacionados a este HPA
                </h3>
              </div>
              {events.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Activity className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Nenhum evento encontrado</p>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Tipo</TableHead>
                      <TableHead>Razão</TableHead>
                      <TableHead>Mensagem</TableHead>
                      <TableHead>Timestamp</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {events.map((event, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          {event.type === 'Warning' ? (
                            <Badge variant="destructive">
                              <AlertCircle className="h-3 w-3 mr-1" />
                              Warning
                            </Badge>
                          ) : (
                            <Badge className="bg-blue-500">
                              <CheckCircle className="h-3 w-3 mr-1" />
                              Normal
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell className="font-medium">
                          {event.reason}
                        </TableCell>
                        <TableCell className="max-w-md">
                          {event.message}
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {formatTimestamp(event.lastTimestamp)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* Condições Card */}
      {hpaDetails.conditions.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <CheckCircle className="h-5 w-5 mr-2" />
              Condições
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Tipo</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Razão</TableHead>
                  <TableHead>Mensagem</TableHead>
                  <TableHead>Última Transição</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {hpaDetails.conditions.map((condition, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">
                      {condition.type}
                    </TableCell>
                    <TableCell>
                      {condition.status === 'True' ? (
                        <Badge className="bg-green-500">True</Badge>
                      ) : (
                        <Badge variant="secondary">False</Badge>
                      )}
                    </TableCell>
                    <TableCell>{condition.reason}</TableCell>
                    <TableCell className="max-w-xs truncate">
                      {condition.message}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatTimestamp(condition.lastTransitionTime)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* YAML Editor */}
      <YamlEditor
        open={yamlDrawerOpen}
        onOpenChange={setYamlDrawerOpen}
        resourceType="hpa"
        resourceName={hpaName || ''}
        namespace={namespaceName || ''}
        title={`YAML do HPA - ${hpaName}`}
        onSave={() => {
          setTimeout(() => {
            fetchHPADetails();
          }, 1000);
        }}
      />
    </div>
  );
}

export default HPADetailsPage;
