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,
  Code,
  CheckCircle,
  Loader2,
  Settings,
  FileText,
  Eye,
  EyeOff,
} from 'lucide-react';

export function DeploymentCreateAdvancedPage() {
  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 [yamlContent, setYamlContent] = useState(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
  namespace: default
  labels:
    app: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: nginx:latest
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "50m"
          limits:
            memory: "128Mi"
            cpu: "100m"`);
  const [showPreview, setShowPreview] = useState(false);
  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 (!yamlContent.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Conteúdo YAML é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    // Basic YAML validation
    if (!yamlContent.includes('apiVersion') || !yamlContent.includes('kind')) {
      showToast({
        title: 'Erro de Validação',
        description: 'YAML deve conter apiVersion e kind',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Update namespace in YAML if different
      let updatedYaml = yamlContent;
      if (selectedNamespace !== 'default') {
        updatedYaml = yamlContent.replace(
          /namespace:\s*\S+/g,
          `namespace: ${selectedNamespace}`
        );
      }

      // Update deployment name in YAML if provided
      if (deploymentName !== 'my-deployment') {
        updatedYaml = updatedYaml.replace(
          /name:\s*my-deployment/g,
          `name: ${deploymentName}`
        );
      }

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

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

      // Validate YAML first
      const validateCommand = `kubectl apply --dry-run=client -f "${tempFileName}"`;
      const validateResult = await executeCommand(validateCommand);

      if (!validateResult.success) {
        await executeCommand(`rm -f "${tempFileName}"`);
        showToast({
          title: 'Erro de Validação YAML',
          description: validateResult.error || 'YAML inválido',
          variant: 'destructive',
        });
        setCreating(false);
        return;
      }

      // 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 Avançado Criado com Sucesso',
          description: `Recursos foram criados no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/workloads/deployments');
      } else {
        showToast({
          title: 'Erro ao Criar Deployment',
          description: result.error || 'Falha ao aplicar o YAML',
          variant: 'destructive',
        });
      }
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  const handleLoadTemplate = (template: string) => {
    switch (template) {
      case 'basic':
        setYamlContent(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName || 'my-deployment'}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName || 'my-app'}
spec:
  replicas: 2
  selector:
    matchLabels:
      app: ${deploymentName || 'my-app'}
  template:
    metadata:
      labels:
        app: ${deploymentName || 'my-app'}
    spec:
      containers:
      - name: ${deploymentName || 'my-container'}
        image: nginx:latest
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "50m"
          limits:
            memory: "128Mi"
            cpu: "100m"`);
        break;
      case 'with-service':
        setYamlContent(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName || 'my-deployment'}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName || 'my-app'}
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ${deploymentName || 'my-app'}
  template:
    metadata:
      labels:
        app: ${deploymentName || 'my-app'}
    spec:
      containers:
      - name: ${deploymentName || 'my-container'}
        image: nginx:latest
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "256Mi"
            cpu: "200m"
---
apiVersion: v1
kind: Service
metadata:
  name: ${deploymentName || 'my-deployment'}-service
  namespace: ${selectedNamespace}
spec:
  selector:
    app: ${deploymentName || 'my-app'}
  ports:
  - port: 80
    targetPort: 80
  type: ClusterIP`);
        break;
      case 'with-configmap':
        setYamlContent(`apiVersion: v1
kind: ConfigMap
metadata:
  name: ${deploymentName || 'my-deployment'}-config
  namespace: ${selectedNamespace}
data:
  config.properties: |
    app.name=${deploymentName || 'my-app'}
    app.environment=production
    log.level=info
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ${deploymentName || 'my-deployment'}
  namespace: ${selectedNamespace}
  labels:
    app: ${deploymentName || 'my-app'}
spec:
  replicas: 2
  selector:
    matchLabels:
      app: ${deploymentName || 'my-app'}
  template:
    metadata:
      labels:
        app: ${deploymentName || 'my-app'}
    spec:
      containers:
      - name: ${deploymentName || 'my-container'}
        image: nginx:latest
        ports:
        - containerPort: 80
        volumeMounts:
        - name: config-volume
          mountPath: /etc/config
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "256Mi"
            cpu: "200m"
      volumes:
      - name: config-volume
        configMap:
          name: ${deploymentName || 'my-deployment'}-config`);
        break;
    }
  };

  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">
              <Code className="h-8 w-8 mr-3 text-gray-600" />
              Criar Deployment Avançado
            </h1>
            <p className="text-muted-foreground">
              Configure um deployment com controle total usando YAML
            </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-advanced-app"
                value={deploymentName}
                onChange={(e) => setDeploymentName(e.target.value)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Será aplicado automaticamente no YAML se usar template
              </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>

      {/* Templates */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <FileText className="h-5 w-5 mr-2" />
            Templates Rápidos
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Button
              variant="outline"
              onClick={() => handleLoadTemplate('basic')}
              className="h-auto p-4 flex flex-col items-start"
            >
              <h4 className="font-medium">Deployment Básico</h4>
              <p className="text-xs text-muted-foreground mt-1">
                Deployment simples com nginx
              </p>
            </Button>
            <Button
              variant="outline"
              onClick={() => handleLoadTemplate('with-service')}
              className="h-auto p-4 flex flex-col items-start"
            >
              <h4 className="font-medium">Com Service</h4>
              <p className="text-xs text-muted-foreground mt-1">
                Deployment + Service ClusterIP
              </p>
            </Button>
            <Button
              variant="outline"
              onClick={() => handleLoadTemplate('with-configmap')}
              className="h-auto p-4 flex flex-col items-start"
            >
              <h4 className="font-medium">Com ConfigMap</h4>
              <p className="text-xs text-muted-foreground mt-1">
                Deployment + ConfigMap + Volume
              </p>
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* YAML Editor */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Code className="h-5 w-5 mr-2" />
              Editor YAML
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowPreview(!showPreview)}
            >
              {showPreview ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}
              {showPreview ? 'Ocultar Preview' : 'Mostrar Preview'}
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="yamlContent">Manifesto YAML</Label>
            <Textarea
              id="yamlContent"
              placeholder="Cole ou edite seu YAML aqui..."
              value={yamlContent}
              onChange={(e) => setYamlContent(e.target.value)}
              className="min-h-[400px] font-mono text-sm"
            />
            <p className="text-xs text-muted-foreground mt-1">
              Suporte completo para múltiplos recursos separados por '---'
            </p>
          </div>

          {showPreview && (
            <div>
              <Label>Preview do YAML</Label>
              <div className="p-4 bg-gray-50 rounded-md border">
                <pre className="text-xs text-gray-700 whitespace-pre-wrap overflow-auto max-h-[300px]">
                  {yamlContent}
                </pre>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Features */}
      <Card>
        <CardHeader>
          <CardTitle>Recursos Avançados</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2 text-sm">
            <p><strong>✓ Controle Total:</strong> Edição completa do manifesto YAML</p>
            <p><strong>✓ Múltiplos Recursos:</strong> Suporte para Deployment, Service, ConfigMap, etc.</p>
            <p><strong>✓ Validação:</strong> Verificação automática antes da aplicação</p>
            <p><strong>✓ Templates:</strong> Pontos de partida para configurações comuns</p>
            <p><strong>✓ Preview:</strong> Visualização do YAML antes da criação</p>
            <p><strong>✓ Namespace Automático:</strong> Aplicação do namespace selecionado</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() || !yamlContent.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Aplicando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Aplicar YAML
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default DeploymentCreateAdvancedPage;