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 { Textarea } from '@/components/ui/textarea';
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,
  Settings,
  CheckCircle,
  Loader2,
  Image,
  Network,
  Plus,
  Trash2,
} from 'lucide-react';

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

export function DeploymentCreateApiPage() {
  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(3);
  const [containerPort, setContainerPort] = useState(8080);
  const [servicePort, setServicePort] = useState(80);
  const [healthPath, setHealthPath] = useState('/health');
  const [readinessPath, setReadinessPath] = useState('/ready');
  const [envVars, setEnvVars] = useState<EnvVar[]>([
    { id: '1', name: 'NODE_ENV', value: 'production' },
    { id: '2', name: 'PORT', value: '8080' },
  ]);
  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: api
spec:
  replicas: ${replicas}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  selector:
    matchLabels:
      app: ${deploymentName}
  template:
    metadata:
      labels:
        app: ${deploymentName}
        tier: api
    spec:
      containers:
      - name: ${deploymentName}
        image: ${containerImage}
        ports:
        - containerPort: ${containerPort}
          name: http
        env:
${envVarsYaml}
        livenessProbe:
          httpGet:
            path: ${healthPath}
            port: ${containerPort}
          initialDelaySeconds: 60
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: ${readinessPath}
            port: ${containerPort}
          initialDelaySeconds: 10
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        resources:
          requests:
            memory: "256Mi"
            cpu: "200m"
          limits:
            memory: "512Mi"
            cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
  name: ${deploymentName}-service
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
    tier: api
spec:
  type: ClusterIP
  ports:
  - port: ${servicePort}
    targetPort: ${containerPort}
    protocol: TCP
    name: http
  selector:
    app: ${deploymentName}`;

      // Create temporary file with the deployment spec
      const tempFileName = `/tmp/deployment-api-${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: 'API/Microservice Criado com Sucesso',
          description: `Deployment e Service "${deploymentName}" foram criados no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar API/Microservice',
          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">
              <Settings className="h-8 w-8 mr-3 text-purple-600" />
              Criar API/Microservice
            </h1>
            <p className="text-muted-foreground">
              Configure uma API REST com configurações de produção
            </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 da API</Label>
              <Input
                id="deploymentName"
                placeholder="ex: user-api, payment-service"
                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: node:18-alpine, python:3.11-slim"
              value={containerImage}
              onChange={(e) => setContainerImage(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Recomendado: node, python, java, golang, php para APIs
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="replicas">Número de Réplicas</Label>
              <Input
                id="replicas"
                type="number"
                min="1"
                max="20"
                value={replicas}
                onChange={(e) => setReplicas(parseInt(e.target.value) || 3)}
              />
            </div>
            <div>
              <Label htmlFor="containerPort">Porta do Container</Label>
              <Input
                id="containerPort"
                type="number"
                placeholder="8080"
                value={containerPort}
                onChange={(e) => setContainerPort(parseInt(e.target.value) || 8080)}
              />
            </div>
            <div>
              <Label htmlFor="servicePort">Porta do Service</Label>
              <Input
                id="servicePort"
                type="number"
                placeholder="80"
                value={servicePort}
                onChange={(e) => setServicePort(parseInt(e.target.value) || 80)}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Health Checks */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Network className="h-5 w-5 mr-2" />
            Health Checks
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="healthPath">Liveness Probe Path</Label>
              <Input
                id="healthPath"
                placeholder="/health"
                value={healthPath}
                onChange={(e) => setHealthPath(e.target.value)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Endpoint para verificar se a aplicação está viva
              </p>
            </div>
            <div>
              <Label htmlFor="readinessPath">Readiness Probe Path</Label>
              <Input
                id="readinessPath"
                placeholder="/ready"
                value={readinessPath}
                onChange={(e) => setReadinessPath(e.target.value)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Endpoint para verificar se a aplicação está pronta
              </p>
            </div>
          </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: API_KEY"
                      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: my-secret-key"
                        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 da API</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>✓ Múltiplas Réplicas:</strong> {replicas} instâncias para alta disponibilidade</p>
            <p><strong>✓ Health Checks Avançados:</strong> Liveness e Readiness probes configurados</p>
            <p><strong>✓ Rolling Updates:</strong> Atualizações sem downtime</p>
            <p><strong>✓ Service ClusterIP:</strong> Comunicação interna otimizada</p>
            <p><strong>✓ Recursos de Produção:</strong> CPU 200m-500m, Memory 256Mi-512Mi</p>
            <p><strong>✓ Variáveis de Ambiente:</strong> Configuração flexível</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 API/Microservice
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateApiPage;