import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { useKubectl, useNamespacesInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Activity,
  CheckCircle,
  Loader2,
  Settings,
  TrendingUp,
  Target,
  Zap,
  Info,
} from 'lucide-react';

export function HPACreatePage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();
  const { namespaces } = useNamespacesInfo();
  const { selectedNamespace: globalNamespace } = useGlobalNamespace();

  const [hpaName, setHpaName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [targetKind, setTargetKind] = useState<'Deployment' | 'StatefulSet'>('Deployment');
  const [targetName, setTargetName] = useState('');
  const [targets, setTargets] = useState<Array<{ name: string; namespace: string }>>([]);
  const [minReplicas, setMinReplicas] = useState(1);
  const [maxReplicas, setMaxReplicas] = useState(10);
  const [cpuTarget, setCpuTarget] = useState(80);
  const [enableMemoryMetric, setEnableMemoryMetric] = useState(false);
  const [memoryTarget, setMemoryTarget] = useState(80);
  const [creating, setCreating] = useState(false);

  // Buscar targets disponíveis quando namespace ou kind mudar
  useEffect(() => {
    const fetchTargets = async () => {
      try {
        const kind = targetKind.toLowerCase();
        const command = `kubectl get ${kind} -n ${selectedNamespace} -o json`;
        const result = await executeCommand(command);

        if (result.success && result.data) {
          const data = JSON.parse(result.data);
          const targetsList = data.items.map((item: any) => ({
            name: item.metadata.name,
            namespace: item.metadata.namespace,
          }));
          setTargets(targetsList);

          // Reset target name se não existir na nova lista
          if (targetName && !targetsList.some((t: any) => t.name === targetName)) {
            setTargetName('');
          }
        }
      } catch (err) {
        console.error('Erro ao buscar targets:', err);
        setTargets([]);
      }
    };

    fetchTargets();
  }, [selectedNamespace, targetKind, executeCommand]);

  const validateForm = () => {
    if (!hpaName.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome do HPA é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    // Validação RFC 1123: lowercase, alfanumérico, hífens e pontos
    const rfc1123Regex = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;
    if (!rfc1123Regex.test(hpaName)) {
      showToast({
        title: 'Nome Inválido',
        description: 'O nome deve conter apenas letras minúsculas, números, hífens (-) e pontos (.). Deve começar e terminar com alfanumérico.',
        variant: 'destructive',
      });
      return false;
    }

    if (!selectedNamespace) {
      showToast({
        title: 'Erro de Validação',
        description: 'Namespace é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!targetName) {
      showToast({
        title: 'Erro de Validação',
        description: 'Target (Deployment/StatefulSet) é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (minReplicas < 1) {
      showToast({
        title: 'Erro de Validação',
        description: 'Mínimo de réplicas deve ser pelo menos 1',
        variant: 'destructive',
      });
      return false;
    }

    if (maxReplicas < minReplicas) {
      showToast({
        title: 'Erro de Validação',
        description: 'Máximo de réplicas deve ser maior ou igual ao mínimo',
        variant: 'destructive',
      });
      return false;
    }

    if (cpuTarget < 1 || cpuTarget > 100) {
      showToast({
        title: 'Erro de Validação',
        description: 'Target de CPU deve estar entre 1% e 100%',
        variant: 'destructive',
      });
      return false;
    }

    if (enableMemoryMetric && (memoryTarget < 1 || memoryTarget > 100)) {
      showToast({
        title: 'Erro de Validação',
        description: 'Target de memória deve estar entre 1% e 100%',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

  const handleCreateHPA = async () => {
    if (!validateForm()) return;

    setCreating(true);
    try {
      const memoryMetricYaml = enableMemoryMetric
        ? `  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: ${memoryTarget}`
        : '';

      const hpaYaml = `apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: ${hpaName}
  namespace: ${selectedNamespace}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: ${targetKind}
    name: ${targetName}
  minReplicas: ${minReplicas}
  maxReplicas: ${maxReplicas}
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: ${cpuTarget}${memoryMetricYaml ? '\n' + memoryMetricYaml : ''}`;

      // Create temporary file with the HPA spec
      const tempFileName = `/tmp/hpa-${hpaName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${hpaYaml}
EOF`;

      const writeResult = await executeCommand(writeCommand);
      if (!writeResult.success) {
        throw new Error('Falha ao criar arquivo temporário');
      }

      // Apply the HPA
      const applyCommand = `kubectl apply -f "${tempFileName}"`;
      const result = await executeCommand(applyCommand);

      // Clean up temp file
      await executeCommand(`rm -f "${tempFileName}"`);

      if (result.success) {
        showToast({
          title: 'HPA Criado com Sucesso',
          description: `HPA "${hpaName}" foi criado no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/hpa');
      } else {
        showToast({
          title: 'Erro ao Criar HPA',
          description: result.error || 'Falha ao criar o HPA',
          variant: 'destructive',
        });
      }
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  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" />
              Criar Horizontal Pod Autoscaler
            </h1>
            <p className="text-muted-foreground">
              Configure autoscaling automático baseado em métricas de CPU e memória
            </p>
          </div>
        </div>
      </div>

      {/* Basic Info */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Settings className="h-5 w-5 mr-2" />
            Informações Básicas
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="hpaName">Nome do HPA</Label>
              <Input
                id="hpaName"
                placeholder="ex: my-app-hpa"
                value={hpaName}
                onChange={(e) => setHpaName(e.target.value.toLowerCase())}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Apenas minúsculas, números, hífens e pontos. Ex: my-app-hpa
              </p>
            </div>
            <div>
              <Label htmlFor="namespace">Namespace</Label>
              <Select
                value={selectedNamespace}
                onValueChange={setSelectedNamespace}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione o namespace" />
                </SelectTrigger>
                <SelectContent>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns.name} value={ns.name}>
                      {ns.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Target Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Target className="h-5 w-5 mr-2" />
            Target de Escalação
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="targetKind">Tipo de Recurso</Label>
              <Select
                value={targetKind}
                onValueChange={(value: 'Deployment' | 'StatefulSet') => setTargetKind(value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Deployment">Deployment</SelectItem>
                  <SelectItem value="StatefulSet">StatefulSet</SelectItem>
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground mt-1">
                Tipo de workload que será escalado
              </p>
            </div>
            <div>
              <Label htmlFor="targetName">Nome do Target</Label>
              <Select
                value={targetName}
                onValueChange={setTargetName}
              >
                <SelectTrigger>
                  <SelectValue placeholder={targets.length > 0 ? "Selecione um target" : "Nenhum target disponível"} />
                </SelectTrigger>
                <SelectContent>
                  {targets.map((target) => (
                    <SelectItem key={target.name} value={target.name}>
                      {target.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground mt-1">
                {targets.length > 0
                  ? `${targets.length} ${targetKind}(s) disponível(is) em ${selectedNamespace}`
                  : `Nenhum ${targetKind} encontrado em ${selectedNamespace}`
                }
              </p>
            </div>
          </div>

          {targetName && (
            <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
              <p className="text-sm text-blue-700">
                <strong>🎯 Target Selecionado:</strong> {targetKind} "{targetName}"
              </p>
              <p className="text-xs text-blue-600 mt-1">
                Este HPA irá escalar automaticamente as réplicas deste {targetKind} baseado nas métricas configuradas
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Replicas Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <TrendingUp className="h-5 w-5 mr-2" />
            Configuração de Réplicas
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="minReplicas">Mínimo de Réplicas</Label>
              <Input
                id="minReplicas"
                type="number"
                min="1"
                value={minReplicas}
                onChange={(e) => setMinReplicas(parseInt(e.target.value) || 1)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Número mínimo de pods sempre em execução
              </p>
            </div>
            <div>
              <Label htmlFor="maxReplicas">Máximo de Réplicas</Label>
              <Input
                id="maxReplicas"
                type="number"
                min={minReplicas}
                value={maxReplicas}
                onChange={(e) => setMaxReplicas(parseInt(e.target.value) || 10)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Número máximo de pods permitido durante picos
              </p>
            </div>
          </div>

          <div className="p-4 bg-gray-50 rounded-md border">
            <h4 className="font-medium text-sm mb-2">Preview da Configuração</h4>
            <div className="text-sm space-y-1">
              <p><strong>Range de Réplicas:</strong> {minReplicas} - {maxReplicas} pods</p>
              <p><strong>Fator de Escalação:</strong> até {Math.floor((maxReplicas / minReplicas) * 100)}% de aumento</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Metrics Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Zap className="h-5 w-5 mr-2" />
            Métricas de Escalação
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* CPU Metric */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label htmlFor="cpuTarget">Target de CPU (Utilização)</Label>
              <span className="text-2xl font-bold text-blue-600">{cpuTarget}%</span>
            </div>
            <input
              type="range"
              id="cpuTarget"
              min="10"
              max="100"
              step="5"
              value={cpuTarget}
              onChange={(e) => setCpuTarget(parseInt(e.target.value))}
              className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
            />
            <p className="text-xs text-muted-foreground">
              Quando a utilização média de CPU ultrapassar {cpuTarget}%, o HPA irá aumentar as réplicas
            </p>
          </div>

          {/* Memory Metric (Optional) */}
          <div className="space-y-3">
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="enableMemory"
                checked={enableMemoryMetric}
                onChange={(e) => setEnableMemoryMetric(e.target.checked)}
                className="h-4 w-4"
              />
              <Label htmlFor="enableMemory" className="cursor-pointer">
                Habilitar métrica de memória
              </Label>
            </div>

            {enableMemoryMetric && (
              <>
                <div className="flex items-center justify-between">
                  <Label htmlFor="memoryTarget">Target de Memória (Utilização)</Label>
                  <span className="text-2xl font-bold text-green-600">{memoryTarget}%</span>
                </div>
                <input
                  type="range"
                  id="memoryTarget"
                  min="10"
                  max="100"
                  step="5"
                  value={memoryTarget}
                  onChange={(e) => setMemoryTarget(parseInt(e.target.value))}
                  className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                />
                <p className="text-xs text-muted-foreground">
                  Quando a utilização média de memória ultrapassar {memoryTarget}%, o HPA irá aumentar as réplicas
                </p>
              </>
            )}
          </div>

          {/* Info Box */}
          <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
            <div className="flex items-start">
              <Info className="h-4 w-4 text-blue-600 mt-0.5 mr-2 flex-shrink-0" />
              <div className="text-sm text-blue-700">
                <p className="font-medium mb-1">Como funciona o HPA?</p>
                <ul className="text-xs text-blue-600 space-y-1">
                  <li>• O HPA verifica as métricas a cada 15 segundos</li>
                  <li>• Se a utilização ultrapassar o target, aumenta as réplicas</li>
                  <li>• Se a utilização ficar abaixo do target, diminui as réplicas</li>
                  <li>• Sempre respeita os limites mínimo e máximo configurados</li>
                </ul>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Actions */}
      <div className="flex items-center justify-between pt-6">
        <Button variant="outline" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Voltar
        </Button>
        <Button
          onClick={handleCreateHPA}
          disabled={creating || !hpaName.trim() || !targetName}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar HPA
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default HPACreatePage;
