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

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

  const [ingressName, setIngressName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [yamlContent, setYamlContent] = useState(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    # Adicione suas anotações personalizadas aqui
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80
  tls:
  - hosts:
    - example.com
    secretName: example-tls`);
  const [showPreview, setShowPreview] = useState(true);
  const [creating, setCreating] = useState(false);

  const validateForm = () => {
    if (!ingressName.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome do Ingress é 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: 'Configuração YAML é obrigatória',
        variant: 'destructive',
      });
      return false;
    }

    // Basic YAML validation
    try {
      // Check if it contains basic Ingress structure
      if (!yamlContent.includes('kind: Ingress')) {
        showToast({
          title: 'Erro de Validação',
          description: 'YAML deve conter "kind: Ingress"',
          variant: 'destructive',
        });
        return false;
      }

      if (!yamlContent.includes('apiVersion:')) {
        showToast({
          title: 'Erro de Validação',
          description: 'YAML deve conter "apiVersion"',
          variant: 'destructive',
        });
        return false;
      }
    } catch (error) {
      showToast({
        title: 'Erro de Validação',
        description: 'YAML inválido',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

  const updateYamlWithBasicInfo = () => {
    let updatedYaml = yamlContent;
    
    // Update name if different
    if (ingressName.trim()) {
      updatedYaml = updatedYaml.replace(
        /name:\s*[^\n]*/,
        `name: ${ingressName}`
      );
    }
    
    // Update namespace if different
    updatedYaml = updatedYaml.replace(
      /namespace:\s*[^\n]*/,
      `namespace: ${selectedNamespace}`
    );
    
    setYamlContent(updatedYaml);
  };

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

    setCreating(true);
    try {
      // Update YAML with current values
      let finalYaml = yamlContent;
      
      // Ensure name and namespace are correct
      finalYaml = finalYaml.replace(
        /name:\s*[^\n]*/,
        `name: ${ingressName}`
      );
      finalYaml = finalYaml.replace(
        /namespace:\s*[^\n]*/,
        `namespace: ${selectedNamespace}`
      );

      // Create temporary file with the YAML
      const tempFileName = `/tmp/ingress-advanced-${ingressName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${finalYaml}
EOF`;

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

      // Apply the ingress
      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: 'Ingress Avançado Criado com Sucesso',
          description: `Ingress "${ingressName}" foi criado no namespace "${selectedNamespace}"`,
          variant: 'success',
        });
        navigate('/service-discovery/ingresses');
      } else {
        showToast({
          title: 'Erro ao Criar Ingress',
          description: result.error || 'Falha ao criar o Ingress',
          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-gray-600" />
              Criar Ingress Avançado
            </h1>
            <p className="text-muted-foreground">
              Configure um Ingress personalizado com YAML completo
            </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="ingressName">Nome do Ingress</Label>
              <Input
                id="ingressName"
                placeholder="ex: my-advanced-ingress"
                value={ingressName}
                onChange={(e) => setIngressName(e.target.value)}
                onBlur={updateYamlWithBasicInfo}
              />
            </div>
            <div>
              <Label htmlFor="namespace">Namespace</Label>
              <Select
                value={selectedNamespace}
                onValueChange={(value) => {
                  setSelectedNamespace(value);
                  // Update YAML when namespace changes
                  setTimeout(updateYamlWithBasicInfo, 100);
                }}
              >
                <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>

      {/* YAML Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Code className="h-5 w-5 mr-2" />
              Configuração YAML
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowPreview(!showPreview)}
            >
              {showPreview ? (
                <EyeOff className="h-4 w-4" />
              ) : (
                <Eye className="h-4 w-4" />
              )}
              {showPreview ? 'Ocultar' : 'Mostrar'} Editor
            </Button>
          </CardTitle>
        </CardHeader>
        {showPreview && (
          <CardContent>
            <div className="space-y-2">
              <Label htmlFor="yamlContent">
                Edite a configuração YAML do Ingress
              </Label>
              <Textarea
                id="yamlContent"
                value={yamlContent}
                onChange={(e) => setYamlContent(e.target.value)}
                rows={25}
                className="font-mono text-sm"
                placeholder="Cole ou edite a configuração YAML do Ingress aqui..."
              />
              <div className="flex items-center space-x-4 text-xs text-muted-foreground">
                <span>💡 Dica: Você pode personalizar anotações, múltiplos hosts, paths complexos, etc.</span>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      {/* Template Examples */}
      <Card>
        <CardHeader>
          <CardTitle>Templates Úteis</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Button
              variant="outline"
              onClick={() => {
                setYamlContent(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName || 'multi-host-ingress'}
  namespace: ${selectedNamespace}
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /v1
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 8080
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend-service
            port:
              number: 80`);
              }}
            >
              Template: Múltiplos Hosts
            </Button>

            <Button
              variant="outline"
              onClick={() => {
                setYamlContent(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName || 'path-based-ingress'}
  namespace: ${selectedNamespace}
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /api(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 8080
      - path: /static(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: static-service
            port:
              number: 80
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend-service
            port:
              number: 80`);
              }}
            >
              Template: Paths Complexos
            </Button>

            <Button
              variant="outline"
              onClick={() => {
                setYamlContent(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName || 'rate-limited-ingress'}
  namespace: ${selectedNamespace}
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
    nginx.ingress.kubernetes.io/auth-basic: "Authentication Required"
    nginx.ingress.kubernetes.io/auth-secret: "basic-auth"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
spec:
  rules:
  - host: secure.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: secure-service
            port:
              number: 80`);
              }}
            >
              Template: Rate Limit + Auth
            </Button>

            <Button
              variant="outline"
              onClick={() => {
                setYamlContent(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName || 'websocket-ingress'}
  namespace: ${selectedNamespace}
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    nginx.ingress.kubernetes.io/websocket-services: "websocket-service"
spec:
  rules:
  - host: ws.example.com
    http:
      paths:
      - path: /ws
        pathType: Prefix
        backend:
          service:
            name: websocket-service
            port:
              number: 8080
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend-service
            port:
              number: 80`);
              }}
            >
              Template: WebSocket
            </Button>
          </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={handleCreateIngress}
          disabled={creating || !ingressName.trim() || !yamlContent.trim()}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Ingress Avançado
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default IngressCreateAdvancedPage;