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, useServicesInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Globe,
  Plus,
  Trash2,
  CheckCircle,
  Loader2,
  Settings,
  Info,
} from 'lucide-react';

interface IngressRule {
  id: string;
  host: string;
  path: string;
  pathType: 'Prefix' | 'Exact' | 'ImplementationSpecific';
  serviceName: string;
  servicePort: number;
}

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

  const [ingressName, setIngressName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [ingressClass, setIngressClass] = useState('');
  const [rules, setRules] = useState<IngressRule[]>([
    {
      id: '1',
      host: '',
      path: '/',
      pathType: 'Prefix',
      serviceName: '',
      servicePort: 80,
    },
  ]);
  const [creating, setCreating] = useState(false);

  const availableServices = services.filter(
    (service) => service.namespace === selectedNamespace
  );

  const addRule = () => {
    const newRule: IngressRule = {
      id: Date.now().toString(),
      host: '',
      path: '/',
      pathType: 'Prefix',
      serviceName: '',
      servicePort: 80,
    };
    setRules([...rules, newRule]);
  };

  const removeRule = (ruleId: string) => {
    if (rules.length > 1) {
      setRules(rules.filter((rule) => rule.id !== ruleId));
    }
  };

  const updateRule = (ruleId: string, updates: Partial<IngressRule>) => {
    setRules(rules.map((rule) => 
      rule.id === ruleId ? { ...rule, ...updates } : rule
    ));
  };

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

    // Validate rules
    for (const rule of rules) {
      if (!rule.serviceName) {
        showToast({
          title: 'Erro de Validação',
          description: 'Serviço é obrigatório para todas as regras',
          variant: 'destructive',
        });
        return false;
      }

      if (!rule.servicePort || rule.servicePort <= 0) {
        showToast({
          title: 'Erro de Validação',
          description: 'Porta do serviço deve ser maior que 0',
          variant: 'destructive',
        });
        return false;
      }
    }

    return true;
  };

  const generateIngressYaml = () => {
    const ingressSpec: any = {
      apiVersion: 'networking.k8s.io/v1',
      kind: 'Ingress',
      metadata: {
        name: ingressName,
        namespace: selectedNamespace,
      },
      spec: {
        rules: rules.map((rule) => ({
          ...(rule.host && { host: rule.host }),
          http: {
            paths: [
              {
                path: rule.path,
                pathType: rule.pathType,
                backend: {
                  service: {
                    name: rule.serviceName,
                    port: {
                      number: rule.servicePort,
                    },
                  },
                },
              },
            ],
          },
        })),
      },
    };

    // Add ingress class if specified
    if (ingressClass) {
      ingressSpec.spec.ingressClassName = ingressClass;
    }

    return ingressSpec;
  };

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

    setCreating(true);
    try {
      const ingressSpec = generateIngressYaml();
      const yamlContent = `# Ingress Simples
${JSON.stringify(ingressSpec, null, 2).replace(/"/g, '')}`;

      // Create temporary file with the spec
      const tempFileName = `/tmp/ingress-${ingressName}-${Date.now()}.yaml`;
      const writeCommand = `cat > "${tempFileName}" << 'EOF'
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName}
  namespace: ${selectedNamespace}
spec:${ingressClass ? `
  ingressClassName: ${ingressClass}` : ''}
  rules:${rules.map((rule) => `
  - ${rule.host ? `host: ${rule.host}` : ''}
    http:
      paths:
      - path: ${rule.path}
        pathType: ${rule.pathType}
        backend:
          service:
            name: ${rule.serviceName}
            port:
              number: ${rule.servicePort}`).join('')}
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 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">
              <Globe className="h-8 w-8 mr-3 text-blue-600" />
              Criar Ingress Simples
            </h1>
            <p className="text-muted-foreground">
              Configure um Ingress HTTP básico para roteamento de tráfego
            </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-3 gap-4">
            <div>
              <Label htmlFor="ingressName">Nome do Ingress</Label>
              <Input
                id="ingressName"
                placeholder="ex: app-ingress"
                value={ingressName}
                onChange={(e) => setIngressName(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>
              <Label htmlFor="ingressClass">Ingress Class (Opcional)</Label>
              <Input
                id="ingressClass"
                placeholder="ex: nginx, traefik"
                value={ingressClass}
                onChange={(e) => setIngressClass(e.target.value)}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Rules */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Globe className="h-5 w-5 mr-2" />
              Regras de Roteamento
            </div>
            <Button onClick={addRule} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              Adicionar Regra
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {rules.map((rule, index) => (
            <Card key={rule.id} className="border-gray-200">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <h4 className="font-medium">Regra {index + 1}</h4>
                  {rules.length > 1 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeRule(rule.id)}
                      className="text-red-600 hover:text-red-800"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>Host (Opcional)</Label>
                    <Input
                      placeholder="ex: app.exemplo.com"
                      value={rule.host}
                      onChange={(e) => updateRule(rule.id, { host: e.target.value })}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      Deixe vazio para aceitar qualquer host
                    </p>
                  </div>
                  <div>
                    <Label>Path</Label>
                    <Input
                      placeholder="ex: /api, /"
                      value={rule.path}
                      onChange={(e) => updateRule(rule.id, { path: e.target.value })}
                    />
                  </div>
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label>Tipo do Path</Label>
                    <Select
                      value={rule.pathType}
                      onValueChange={(value) => updateRule(rule.id, { pathType: value as any })}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Prefix">Prefix</SelectItem>
                        <SelectItem value="Exact">Exact</SelectItem>
                        <SelectItem value="ImplementationSpecific">Implementation Specific</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Serviço</Label>
                    <Select
                      value={rule.serviceName}
                      onValueChange={(value) => updateRule(rule.id, { serviceName: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Selecione o serviço" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableServices.map((service) => (
                          <SelectItem key={service.name} value={service.name}>
                            {service.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label>Porta do Serviço</Label>
                    <Input
                      type="number"
                      placeholder="80"
                      value={rule.servicePort}
                      onChange={(e) => updateRule(rule.id, { servicePort: parseInt(e.target.value) || 0 })}
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </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() || rules.some(r => !r.serviceName)}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Ingress
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default IngressCreateSimplePage;