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,
  Zap,
  CheckCircle,
  Loader2,
  Settings,
  Image,
  Network,
} from 'lucide-react';

export function DeploymentCreateWebappPage() {
  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(2);
  const [containerPort, setContainerPort] = useState(8080);
  const [servicePort, setServicePort] = useState(80);
  const [creating, setCreating] = useState(false);

  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 {
      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:
      containers:
      - name: ${deploymentName}
        image: ${containerImage}
        ports:
        - containerPort: ${containerPort}
        livenessProbe:
          httpGet:
            path: /
            port: ${containerPort}
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /
            port: ${containerPort}
          initialDelaySeconds: 10
          periodSeconds: 5
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "256Mi"
            cpu: "200m"
---
apiVersion: v1
kind: Service
metadata:
  name: ${deploymentName}-service
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName}
spec:
  type: ClusterIP
  ports:
  - port: ${servicePort}
    targetPort: ${containerPort}
    protocol: TCP
  selector:
    app: ${deploymentName}`;

      // Create temporary file with the deployment spec
      const tempFileName = `/tmp/deployment-webapp-${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: 'Aplicação Web Criada com Sucesso',
          description: `Deployment e Service "${deploymentName}" foram criados no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar Aplicação Web',
          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">
              <Zap className="h-8 w-8 mr-3 text-green-600" />
              Criar Aplicação Web
            </h1>
            <p className="text-muted-foreground">
              Configure uma aplicação web com Service e health checks
            </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 Aplicação</Label>
              <Input
                id="deploymentName"
                placeholder="ex: my-webapp"
                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, node:18-alpine"
              value={containerImage}
              onChange={(e) => setContainerImage(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Recomendado: nginx, httpd, node, php, python web frameworks
            </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="10"
                value={replicas}
                onChange={(e) => setReplicas(parseInt(e.target.value) || 2)}
              />
            </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>

      {/* Service Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Network className="h-5 w-5 mr-2" />
            Configuração do Service
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="p-3 bg-green-50 rounded-md border border-green-200">
            <p className="text-sm text-green-700">
              <strong>Service incluído:</strong> {deploymentName || '<app-name>'}-service
            </p>
            <p className="text-xs text-green-600 mt-1">
              Tipo: ClusterIP | Porta: {servicePort} → {containerPort}
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Features Summary */}
      <Card>
        <CardHeader>
          <CardTitle>Características da Aplicação Web</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>✓ Health Checks:</strong> Liveness e Readiness probes configurados</p>
            <p><strong>✓ Service:</strong> ClusterIP automático para comunicação interna</p>
            <p><strong>✓ Recursos:</strong> CPU 100m-200m, Memory 128Mi-256Mi por pod</p>
            <p><strong>✓ Alta Disponibilidade:</strong> {replicas} réplicas por padrão</p>
            <p><strong>✓ Load Balancing:</strong> Distribuição automática de tráfego</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 Aplicação Web
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateWebappPage;