import React, { useState } 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,
  Layers,
  CheckCircle,
  Loader2,
  Settings,
  Image,
  Zap,
  Plus,
  Trash2,
} from 'lucide-react';

interface EnvVar {
  id: string;
  name: string;
  value: string;
}

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

  const [deploymentName, setDeploymentName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [containerImage, setContainerImage] = useState('');
  const [replicas, setReplicas] = useState(1);
  const [minReplicas, setMinReplicas] = useState(1);
  const [maxReplicas, setMaxReplicas] = useState(10);
  const [cpuThreshold, setCpuThreshold] = useState(70);
  const [envVars, setEnvVars] = useState<EnvVar[]>([
    { id: '1', name: 'WORKER_TYPE', value: 'background' },
    { id: '2', name: 'QUEUE_NAME', value: 'default' },
  ]);
  const [creating, setCreating] = useState(false);

  const addEnvVar = () => {
    const newEnvVar: EnvVar = {
      id: Date.now().toString(),
      name: '',
      value: '',
    };
    setEnvVars([...envVars, newEnvVar]);
  };

  const removeEnvVar = (envId: string) => {
    setEnvVars(envVars.filter((env) => env.id !== envId));
  };

  const updateEnvVar = (envId: string, updates: Partial<EnvVar>) => {
    setEnvVars(envVars.map((env) => 
      env.id === envId ? { ...env, ...updates } : env
    ));
  };

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

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

    if (!containerImage.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Imagem do container é obrigatória',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Build environment variables
      const envVarsYaml = envVars
        .filter(env => env.name.trim() && env.value.trim())
        .map(env => `        - name: ${env.name}\n          value: "${env.value}"`)
        .join('\n');

      const deploymentYaml = `apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
    tier: worker
spec:
  replicas: ${replicas}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  selector:
    matchLabels:
      app: ${deploymentName}
  template:
    metadata:
      labels:
        app: ${deploymentName}
        tier: worker
    spec:
      containers:
      - name: ${deploymentName}
        image: ${containerImage}
        env:
${envVarsYaml}
        livenessProbe:
          exec:
            command:
            - pgrep
            - -f
            - ${deploymentName}
          initialDelaySeconds: 30
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "1000m"
        restartPolicy: Always
      restartPolicy: Always
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: ${deploymentName}-hpa
  namespace: ${selectedNamespace}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ${deploymentName}
  minReplicas: ${minReplicas}
  maxReplicas: ${maxReplicas}
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: ${cpuThreshold}
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
      - type: Percent
        value: 100
        periodSeconds: 15
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Percent
        value: 10
        periodSeconds: 60`;

      // Create temporary file with the deployment spec
      const tempFileName = `/tmp/deployment-worker-${deploymentName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${deploymentYaml}
EOF`;

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

      // Apply the deployment
      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: 'Worker/Background Criado com Sucesso',
          description: `Deployment e HPA "${deploymentName}" foram criados no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar Worker/Background',
          description: result.error || 'Falha ao criar o Deployment',
          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">
              <Layers className="h-8 w-8 mr-3 text-red-600" />
              Criar Worker/Background
            </h1>
            <p className="text-muted-foreground">
              Configure um worker para processamento em background e filas
            </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="deploymentName">Nome do Worker</Label>
              <Input
                id="deploymentName"
                placeholder="ex: queue-worker, background-processor"
                value={deploymentName}
                onChange={(e) => setDeploymentName(e.target.value)}
              />
            </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>

      {/* Container Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Image className="h-5 w-5 mr-2" />
            Configuração do Container
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="containerImage">Imagem do Container</Label>
            <Input
              id="containerImage"
              placeholder="ex: python:3.11-slim, node:18-alpine"
              value={containerImage}
              onChange={(e) => setContainerImage(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Recomendado: python, node, java, golang para workers
            </p>
          </div>
          
          <div>
            <Label htmlFor="replicas">Réplicas Iniciais</Label>
            <Input
              id="replicas"
              type="number"
              min="1"
              max="20"
              value={replicas}
              onChange={(e) => setReplicas(parseInt(e.target.value) || 1)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Auto Scaling Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Zap className="h-5 w-5 mr-2" />
            Configuração de Auto-Scaling
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="minReplicas">Mínimo de Réplicas</Label>
              <Input
                id="minReplicas"
                type="number"
                min="1"
                max="50"
                value={minReplicas}
                onChange={(e) => setMinReplicas(parseInt(e.target.value) || 1)}
              />
            </div>
            <div>
              <Label htmlFor="maxReplicas">Máximo de Réplicas</Label>
              <Input
                id="maxReplicas"
                type="number"
                min="1"
                max="100"
                value={maxReplicas}
                onChange={(e) => setMaxReplicas(parseInt(e.target.value) || 10)}
              />
            </div>
            <div>
              <Label htmlFor="cpuThreshold">Limite de CPU (%)</Label>
              <Input
                id="cpuThreshold"
                type="number"
                min="10"
                max="100"
                value={cpuThreshold}
                onChange={(e) => setCpuThreshold(parseInt(e.target.value) || 70)}
              />
            </div>
          </div>
          <div className="p-3 bg-red-50 rounded-md border border-red-200">
            <p className="text-sm text-red-700">
              <strong>⚡ Auto-scaling:</strong> Escala automaticamente entre {minReplicas} e {maxReplicas} réplicas
            </p>
            <p className="text-xs text-red-600 mt-1">
              Trigger: Quando CPU {'>'}  {cpuThreshold}% | Cooldown: 60s para scale-up, 5min para scale-down
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Environment Variables */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Settings className="h-5 w-5 mr-2" />
              Variáveis de Ambiente
            </div>
            <Button onClick={addEnvVar} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              Adicionar
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {envVars.map((envVar, index) => (
            <Card key={envVar.id} className="border-gray-200">
              <CardContent className="pt-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
                  <div>
                    <Label>Nome</Label>
                    <Input
                      placeholder="ex: REDIS_URL"
                      value={envVar.name}
                      onChange={(e) => updateEnvVar(envVar.id, { name: e.target.value })}
                    />
                  </div>
                  <div>
                    <Label>Valor</Label>
                    <div className="flex gap-2">
                      <Input
                        placeholder="ex: redis://redis:6379"
                        value={envVar.value}
                        onChange={(e) => updateEnvVar(envVar.id, { value: e.target.value })}
                      />
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => removeEnvVar(envVar.id)}
                        className="text-red-600 hover:text-red-800"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </CardContent>
      </Card>

      {/* Features Summary */}
      <Card>
        <CardHeader>
          <CardTitle>Características do Worker</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>✓ Sem Service:</strong> Worker não precisa de comunicação HTTP</p>
            <p><strong>✓ Auto-scaling:</strong> HPA baseado em CPU para alta demanda</p>
            <p><strong>✓ Tolerância a Falhas:</strong> Rolling updates sem interrupção</p>
            <p><strong>✓ Health Checks:</strong> Liveness probe para detectar travamentos</p>
            <p><strong>✓ Recursos Flexíveis:</strong> CPU 100m-1000m, Memory 128Mi-512Mi</p>
            <p><strong>✓ Ambiente Configurável:</strong> Variáveis para filas e configurações</p>
          </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={handleCreateDeployment}
          disabled={creating || !deploymentName.trim() || !containerImage.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Worker/Background
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateWorkerPage;