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 {
  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 { useKubectl } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  Loader2,
  Activity,
  AlertCircle,
  RefreshCw,
  Filter,
  CheckCircle,
  XCircle,
  MoreVertical,
  Trash2,
  TrendingUp,
  TrendingDown,
  Minus,
  Eye,
} from 'lucide-react';

interface HPA {
  name: string;
  namespace: string;
  targetKind: string;
  targetName: string;
  minReplicas: number;
  maxReplicas: number;
  currentReplicas: number;
  desiredReplicas: number;
  metrics: string[];
  age: string;
  isOrphan: boolean;
}

export function HPAsPage() {
  const navigate = useNavigate();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();
  const [hpas, setHpas] = useState<HPA[]>([]);
  const [namespaces, setNamespaces] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [hpaToDelete, setHpaToDelete] = useState<{
    name: string;
    namespace: string;
  } | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const fetchHPAs = async () => {
    setLoading(true);
    setError(null);
    try {
      // Buscar namespaces
      const nsResponse = await executeCommand('kubectl get namespaces -o json');
      if (nsResponse.success && nsResponse.data) {
        const nsData = JSON.parse(nsResponse.data);
        const nsList = nsData.items.map((ns: any) => ns.metadata.name);
        setNamespaces(nsList);
      }

      // Buscar HPAs
      const hpaCommand =
        selectedNamespace === 'all'
          ? 'kubectl get hpa --all-namespaces -o json'
          : `kubectl get hpa -n ${selectedNamespace} -o json`;

      const hpaResponse = await executeCommand(hpaCommand);

      if (hpaResponse.success && hpaResponse.data) {
        const hpaData = JSON.parse(hpaResponse.data);

        // Processar HPAs e verificar se targets existem
        const hpaList: HPA[] = await Promise.all(
          hpaData.items.map(async (hpa: any) => {
            const creationTime = new Date(hpa.metadata.creationTimestamp);
            const now = new Date();
            const diffMs = now.getTime() - creationTime.getTime();
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
            const age = diffDays === 0
              ? `${Math.floor(diffMs / (1000 * 60 * 60))}h`
              : `${diffDays}d`;

            const metrics = hpa.spec.metrics?.map((m: any) => {
              if (m.type === 'Resource') {
                return `${m.resource.name}: ${m.resource.target.averageUtilization || m.resource.target.averageValue}`;
              }
              return m.type;
            }) || [];

            // Verificar se o target existe
            const targetKind = hpa.spec.scaleTargetRef.kind.toLowerCase();
            const targetName = hpa.spec.scaleTargetRef.name;
            const namespace = hpa.metadata.namespace;

            let isOrphan = false;
            try {
              const targetCheckCmd = `kubectl get ${targetKind} ${targetName} -n ${namespace} --ignore-not-found -o json`;
              const targetResponse = await executeCommand(targetCheckCmd);

              if (targetResponse.success && targetResponse.data) {
                const targetData = JSON.parse(targetResponse.data);
                // Se o objeto retornado está vazio ou não tem metadata, o target não existe
                isOrphan = !targetData || !targetData.metadata || !targetData.metadata.name;
              } else {
                // Se houve erro ou não retornou dados, assumir que é órfão
                isOrphan = true;
              }
            } catch (err) {
              // Em caso de erro, assumir que é órfão
              isOrphan = true;
            }

            return {
              name: hpa.metadata.name,
              namespace: hpa.metadata.namespace,
              targetKind: hpa.spec.scaleTargetRef.kind,
              targetName: hpa.spec.scaleTargetRef.name,
              minReplicas: hpa.spec.minReplicas || 1,
              maxReplicas: hpa.spec.maxReplicas,
              currentReplicas: hpa.status.currentReplicas || 0,
              desiredReplicas: hpa.status.desiredReplicas || 0,
              metrics,
              age,
              isOrphan,
            };
          })
        );

        setHpas(hpaList);
      } else {
        setError(hpaResponse.error || 'Erro ao buscar HPAs');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erro desconhecido');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchHPAs();
  }, [selectedNamespace]);

  // Validate namespace
  useEffect(() => {
    if (namespaces.length > 0 && selectedNamespace !== 'all') {
      if (!namespaces.includes(selectedNamespace)) {
        setSelectedNamespace('all');
      }
    }
  }, [namespaces, selectedNamespace, setSelectedNamespace]);

  const handleDeleteClick = (hpaName: string, namespaceName: string) => {
    setHpaToDelete({ name: hpaName, namespace: namespaceName });
    setDeleteModalOpen(true);
  };

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

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

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

  const filteredHPAs = useMemo(() => {
    let filtered = hpas;

    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (hpa) =>
          hpa.name.toLowerCase().includes(query) ||
          hpa.namespace.toLowerCase().includes(query) ||
          hpa.targetName.toLowerCase().includes(query),
      );
    }

    return filtered;
  }, [hpas, searchQuery]);

  const getScalingStatus = (hpa: HPA) => {
    // Órfão tem prioridade máxima no status
    if (hpa.isOrphan) {
      return (
        <Badge variant="destructive">
          <AlertCircle className="h-3 w-3 mr-1" />
          Órfão
        </Badge>
      );
    }

    if (hpa.currentReplicas < hpa.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 (hpa.currentReplicas > hpa.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>
      );
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-foreground">
              Horizontal Pod Autoscalers
            </h1>
            <p className="text-muted-foreground">
              Gerenciar autoscaling de pods
            </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 HPAs...</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">
              Horizontal Pod Autoscalers
            </h1>
            <p className="text-muted-foreground">
              Gerenciar autoscaling de pods
            </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 HPAs
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-500 mb-4">{error}</p>
            <Button onClick={fetchHPAs} variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" />
              Tentar novamente
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">
            Horizontal Pod Autoscalers
          </h1>
          <p className="text-muted-foreground">
            Gerenciar {filteredHPAs.length} HPA(s){' '}
            {selectedNamespace !== 'all'
              ? `no namespace ${selectedNamespace}`
              : 'em todos os namespaces'}
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Button onClick={fetchHPAs} variant="outline">
            <RefreshCw className="h-4 w-4 mr-2" />
            Atualizar
          </Button>
          <Button onClick={() => navigate('/workloads/hpa/create')}>
            <Activity className="h-4 w-4 mr-2" />
            Criar HPA
          </Button>
        </div>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total HPAs</CardTitle>
            <Activity className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{filteredHPAs.length}</div>
            <p className="text-xs text-muted-foreground">Autoscalers ativos</p>
          </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>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filteredHPAs.reduce((sum, hpa) => sum + hpa.currentReplicas, 0)}
            </div>
            <p className="text-xs text-muted-foreground">Total 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">
              Capacidade Máxima
            </CardTitle>
            <TrendingUp className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filteredHPAs.reduce((sum, hpa) => sum + hpa.maxReplicas, 0)}
            </div>
            <p className="text-xs text-muted-foreground">
              Réplicas máximas configuradas
            </p>
          </CardContent>
        </Card>

        <Card className={filteredHPAs.filter((hpa) => hpa.isOrphan).length > 0 ? "border-red-200" : ""}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              HPAs Órfãos
            </CardTitle>
            <XCircle className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filteredHPAs.filter((hpa) => hpa.isOrphan).length}
            </div>
            <p className="text-xs text-muted-foreground">
              Sem target válido
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Filters Card */}
      <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">Buscar</label>
              <Input
                type="text"
                placeholder="Nome do HPA, namespace, target..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* HPAs Table */}
      <Card>
        <CardHeader>
          <CardTitle>Lista de HPAs</CardTitle>
          <CardDescription>
            {filteredHPAs.length} HPA(s) encontrado(s)
            {selectedNamespace !== 'all' && ` em ${selectedNamespace}`}
            {searchQuery && ` contendo "${searchQuery}"`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nome</TableHead>
                <TableHead>Namespace</TableHead>
                <TableHead>Target</TableHead>
                <TableHead>Min/Max</TableHead>
                <TableHead>Réplicas</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-24">Idade</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredHPAs.map((hpa, index) => (
                <TableRow
                  key={index}
                  className={hpa.isOrphan ? "bg-red-50 hover:bg-red-100" : ""}
                >
                  <TableCell className="font-medium">
                    <div
                      className="flex items-center space-x-2 cursor-pointer hover:text-blue-600 transition-colors"
                      onClick={() =>
                        navigate(`/workloads/hpa/${hpa.namespace}/${hpa.name}`)
                      }
                      title="Clique para ver detalhes"
                    >
                      {hpa.isOrphan ? (
                        <AlertCircle className="h-4 w-4 text-red-600" />
                      ) : (
                        <Activity className="h-4 w-4 text-blue-600" />
                      )}
                      <span className="hover:underline">{hpa.name}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className="text-xs">
                      {hpa.namespace}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div className={`font-medium ${hpa.isOrphan ? 'text-red-600 line-through' : ''}`}>
                        {hpa.targetName}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {hpa.targetKind}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">
                    {hpa.minReplicas} / {hpa.maxReplicas}
                  </TableCell>
                  <TableCell className="text-sm">
                    <div className="flex items-center space-x-1">
                      {hpa.currentReplicas === hpa.desiredReplicas ? (
                        <CheckCircle className="h-3 w-3 text-green-600" />
                      ) : (
                        <RefreshCw className="h-3 w-3 text-blue-600 animate-spin" />
                      )}
                      <span>
                        {hpa.currentReplicas} / {hpa.desiredReplicas}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>{getScalingStatus(hpa)}</TableCell>
                  <TableCell className="text-sm">{hpa.age}</TableCell>
                  <TableCell className="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon">
                          <MoreVertical className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuLabel>Ações do HPA</DropdownMenuLabel>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          onClick={() =>
                            navigate(`/workloads/hpa/${hpa.namespace}/${hpa.name}`)
                          }
                        >
                          <Eye className="h-4 w-4 mr-2" />
                          Visualizar
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          onClick={() => handleDeleteClick(hpa.name, hpa.namespace)}
                          className="text-red-600"
                        >
                          <Trash2 className="h-4 w-4 mr-2" />
                          Deletar
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          {filteredHPAs.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 HPA encontrado</p>
              {(searchQuery || selectedNamespace !== 'all') && (
                <p className="text-sm mt-1">
                  Tente ajustar os filtros para ver mais resultados
                </p>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 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 HPA{' '}
              <strong>"{hpaToDelete?.name}"</strong> do namespace{' '}
              <strong>"{hpaToDelete?.namespace}"</strong>?
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            {hpas.find((h) => h.name === hpaToDelete?.name && h.namespace === hpaToDelete?.namespace)?.isOrphan ? (
              <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                <div className="flex items-start">
                  <AlertCircle className="h-5 w-5 text-red-600 mt-0.5 mr-2 flex-shrink-0" />
                  <div className="text-sm text-red-800">
                    <p className="font-medium mb-1">HPA Órfão Detectado:</p>
                    <p>
                      Este HPA está órfão (seu target não existe mais). É recomendado deletá-lo
                      para manter o cluster organizado.
                    </p>
                  </div>
                </div>
              </div>
            ) : (
              <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>
                      Ao deletar este HPA, o autoscaling automático do deployment
                      será desativado. As réplicas atuais permanecerão, mas não
                      serão mais ajustadas automaticamente.
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setDeleteModalOpen(false);
                setHpaToDelete(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>
  );
}
