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, useSecretsInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Container,
  CheckCircle,
  Loader2,
  Settings,
  Image,
  Key,
} from 'lucide-react';

export function DeploymentCreateSimplePage() {
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { executeCommand } = useKubectl();
  const { namespaces } = useNamespacesInfo();
  const { secrets } = useSecretsInfo();
  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 [containerPort, setContainerPort] = useState(80);
  const [selectedImagePullSecret, setSelectedImagePullSecret] = useState(() => {
    return localStorage.getItem('deployment-simple-imagePullSecret') || 'none';
  });
  const [cpuRequest, setCpuRequest] = useState('50m');
  const [cpuLimit, setCpuLimit] = useState('100m');
  const [memoryRequest, setMemoryRequest] = useState('64Mi');
  const [memoryLimit, setMemoryLimit] = useState('128Mi');
  const [creating, setCreating] = useState(false);

  // Persistir a escolha do Image Pull Secret
  React.useEffect(() => {
    if (selectedImagePullSecret !== 'none') {
      localStorage.setItem('deployment-simple-imagePullSecret', selectedImagePullSecret);
    } else {
      localStorage.removeItem('deployment-simple-imagePullSecret');
    }
  }, [selectedImagePullSecret]);

  // Filtrar secrets de registry do namespace selecionado
  const registrySecrets = React.useMemo(() => {
    return secrets.filter(secret => 
      secret.namespace === selectedNamespace && 
      (secret.type === 'kubernetes.io/dockerconfigjson' || secret.type === 'kubernetes.io/dockercfg')
    );
  }, [secrets, selectedNamespace]);

  // Resetar secret selecionado se não existir no novo namespace
  React.useEffect(() => {
    if (selectedImagePullSecret !== 'none') {
      const secretExists = registrySecrets.some(secret => secret.name === selectedImagePullSecret);
      if (!secretExists) {
        setSelectedImagePullSecret('none');
      }
    }
  }, [selectedNamespace, registrySecrets, selectedImagePullSecret]);

  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;
    }

    if (replicas < 1 || replicas > 10) {
      showToast({
        title: 'Erro de Validação',
        description: 'Número de réplicas deve estar entre 1 e 10',
        variant: 'destructive',
      });
      return false;
    }

    if (containerPort <= 0 || containerPort > 65535) {
      showToast({
        title: 'Erro de Validação',
        description: 'Porta do container deve estar entre 1 e 65535',
        variant: 'destructive',
      });
      return false;
    }

    // Validate resource values
    if (!cpuRequest.trim() || !cpuLimit.trim() || !memoryRequest.trim() || !memoryLimit.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Todos os campos de recursos são obrigatórios',
        variant: 'destructive',
      });
      return false;
    }

    // Basic format validation for CPU (should contain 'm' or be a decimal)
    const cpuRequestValid = /^(\d+m|\d*\.?\d+)$/.test(cpuRequest);
    const cpuLimitValid = /^(\d+m|\d*\.?\d+)$/.test(cpuLimit);
    
    if (!cpuRequestValid || !cpuLimitValid) {
      showToast({
        title: 'Erro de Validação',
        description: 'Formato de CPU inválido. Use: 100m, 0.1, 1, etc.',
        variant: 'destructive',
      });
      return false;
    }

    // Basic format validation for Memory (should contain Mi, Gi, etc.)
    const memoryRequestValid = /^\d+(Mi|Gi|Ki|M|G|K)$/i.test(memoryRequest);
    const memoryLimitValid = /^\d+(Mi|Gi|Ki|M|G|K)$/i.test(memoryLimit);
    
    if (!memoryRequestValid || !memoryLimitValid) {
      showToast({
        title: 'Erro de Validação',
        description: 'Formato de memória inválido. Use: 64Mi, 1Gi, 512Mi, etc.',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Build imagePullSecrets section
      const imagePullSecretsYaml = selectedImagePullSecret !== 'none' 
        ? `      imagePullSecrets:
      - name: ${selectedImagePullSecret}` 
        : '';

      const deploymentYaml = `apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
spec:
  replicas: ${replicas}
  selector:
    matchLabels:
      app: ${deploymentName}
  template:
    metadata:
      labels:
        app: ${deploymentName}
    spec:
${imagePullSecretsYaml}
      containers:
      - name: ${deploymentName}
        image: ${containerImage}
        ports:
        - containerPort: ${containerPort}
        resources:
          requests:
            memory: "${memoryRequest}"
            cpu: "${cpuRequest}"
          limits:
            memory: "${memoryLimit}"
            cpu: "${cpuLimit}"`;

      // Create temporary file with the deployment spec
      const tempFileName = `/tmp/deployment-simple-${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: 'Deployment Criado com Sucesso',
          description: `Deployment "${deploymentName}" foi criado no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar Deployment',
          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">
              <Container className="h-8 w-8 mr-3 text-blue-600" />
              Criar Deployment Simples
            </h1>
            <p className="text-muted-foreground">
              Configure uma aplicação básica com configuração mínima
            </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 Deployment</Label>
              <Input
                id="deploymentName"
                placeholder="ex: my-app"
                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: nginx:latest"
              value={containerImage}
              onChange={(e) => setContainerImage(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Exemplo: nginx:latest, httpd:alpine, node:18-alpine
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="replicas">Número de Réplicas</Label>
              <Input
                id="replicas"
                type="number"
                min="1"
                max="10"
                value={replicas}
                onChange={(e) => setReplicas(parseInt(e.target.value) || 1)}
              />
            </div>
            <div>
              <Label htmlFor="containerPort">Porta do Container</Label>
              <Input
                id="containerPort"
                type="number"
                placeholder="80"
                value={containerPort}
                onChange={(e) => setContainerPort(parseInt(e.target.value) || 80)}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Image Pull Secret */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Key className="h-5 w-5 mr-2" />
            Image Pull Secret
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="imagePullSecret">Secret para Registry Privado</Label>
            <Select
              value={selectedImagePullSecret}
              onValueChange={setSelectedImagePullSecret}
            >
              <SelectTrigger>
                <SelectValue placeholder="Selecione um secret" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">
                  <div className="flex items-center">
                    <span className="text-green-600 mr-2">✓</span>
                    Nenhum (imagem pública)
                  </div>
                </SelectItem>
                {registrySecrets.map((secret) => (
                  <SelectItem key={secret.name} value={secret.name}>
                    <div className="flex items-center">
                      <Key className="h-3 w-3 mr-2" />
                      {secret.name}
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground mt-1">
              {selectedImagePullSecret === 'none' 
                ? 'Usando imagem pública - nenhuma autenticação necessária'
                : registrySecrets.length === 0 
                  ? 'Nenhum secret de registry encontrado no namespace selecionado'
                  : `Secret selecionado: ${selectedImagePullSecret}`
              }
            </p>
          </div>
          
          {selectedImagePullSecret !== 'none' && (
            <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
              <p className="text-sm text-blue-700">
                <strong>🔐 Registry Privado:</strong> Usando secret "{selectedImagePullSecret}" para autenticação
              </p>
              <p className="text-xs text-blue-600 mt-1">
                Este secret será usado para fazer pull de imagens de registries privados
              </p>
            </div>
          )}

          {registrySecrets.length === 0 && (
            <div className="p-3 bg-yellow-50 rounded-md border border-yellow-200">
              <p className="text-sm text-yellow-700">
                <strong>ℹ️ Dica:</strong> Nenhum secret de registry encontrado no namespace "{selectedNamespace}"
              </p>
              <p className="text-xs text-yellow-600 mt-1">
                Para usar imagens privadas, crie um secret do tipo docker-registry primeiro
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Resources Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Settings className="h-5 w-5 mr-2" />
            Configuração de Recursos
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Resource Presets */}
          <div>
            <Label>Templates de Recursos</Label>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-2 mt-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setCpuRequest('50m');
                  setCpuLimit('100m');
                  setMemoryRequest('64Mi');
                  setMemoryLimit('128Mi');
                }}
                className="text-xs"
              >
                💼 Micro (Padrão)
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setCpuRequest('100m');
                  setCpuLimit('200m');
                  setMemoryRequest('128Mi');
                  setMemoryLimit('256Mi');
                }}
                className="text-xs"
              >
                📱 Pequeno
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setCpuRequest('250m');
                  setCpuLimit('500m');
                  setMemoryRequest('256Mi');
                  setMemoryLimit('512Mi');
                }}
                className="text-xs"
              >
                💻 Médio
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setCpuRequest('500m');
                  setCpuLimit('1');
                  setMemoryRequest('512Mi');
                  setMemoryLimit('1Gi');
                }}
                className="text-xs"
              >
                🚀 Grande
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* CPU Configuration */}
            <div className="space-y-3">
              <h4 className="font-medium text-sm flex items-center">
                <span className="text-blue-600 mr-2">⚡</span>
                CPU
              </h4>
              <div className="space-y-3">
                <div>
                  <Label htmlFor="cpuRequest">CPU Request</Label>
                  <Input
                    id="cpuRequest"
                    placeholder="ex: 50m, 0.1, 100m"
                    value={cpuRequest}
                    onChange={(e) => setCpuRequest(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Mínimo garantido de CPU
                  </p>
                </div>
                <div>
                  <Label htmlFor="cpuLimit">CPU Limit</Label>
                  <Input
                    id="cpuLimit"
                    placeholder="ex: 100m, 0.2, 200m"
                    value={cpuLimit}
                    onChange={(e) => setCpuLimit(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Máximo permitido de CPU
                  </p>
                </div>
              </div>
            </div>

            {/* Memory Configuration */}
            <div className="space-y-3">
              <h4 className="font-medium text-sm flex items-center">
                <span className="text-green-600 mr-2">🧠</span>
                Memory
              </h4>
              <div className="space-y-3">
                <div>
                  <Label htmlFor="memoryRequest">Memory Request</Label>
                  <Input
                    id="memoryRequest"
                    placeholder="ex: 64Mi, 128Mi, 256Mi"
                    value={memoryRequest}
                    onChange={(e) => setMemoryRequest(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Mínimo garantido de memória
                  </p>
                </div>
                <div>
                  <Label htmlFor="memoryLimit">Memory Limit</Label>
                  <Input
                    id="memoryLimit"
                    placeholder="ex: 128Mi, 256Mi, 512Mi"
                    value={memoryLimit}
                    onChange={(e) => setMemoryLimit(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Máximo permitido de memória
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Resources Summary */}
          <div className="mt-6 p-4 bg-gray-50 rounded-md border">
            <h4 className="font-medium text-sm mb-3">Resumo dos Recursos</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div className="space-y-1">
                <p><strong>CPU Request:</strong> {cpuRequest} per pod</p>
                <p><strong>CPU Limit:</strong> {cpuLimit} per pod</p>
              </div>
              <div className="space-y-1">
                <p><strong>Memory Request:</strong> {memoryRequest} per pod</p>
                <p><strong>Memory Limit:</strong> {memoryLimit} per pod</p>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t border-gray-200">
              <p className="text-sm"><strong>Total Pods:</strong> {replicas}</p>
              <p className="text-xs text-muted-foreground mt-1">
                Total de recursos: CPU {cpuRequest}-{cpuLimit} × {replicas}, Memory {memoryRequest}-{memoryLimit} × {replicas}
              </p>
            </div>
          </div>

          {/* Resource Guidelines */}
          <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
            <p className="text-sm text-blue-700">
              <strong>💡 Dicas de Recursos:</strong>
            </p>
            <ul className="text-xs text-blue-600 mt-1 space-y-1">
              <li>• CPU: Use 'm' para milicores (ex: 100m = 0.1 core)</li>
              <li>• Memory: Use Mi/Gi para mebibytes/gibibytes (ex: 128Mi, 1Gi)</li>
              <li>• Requests: Recursos garantidos (afeta scheduling)</li>
              <li>• Limits: Máximo permitido (evita sobrecarga do nó)</li>
            </ul>
          </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 Deployment
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateSimplePage;