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 { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { useKubectl, useNamespacesInfo, useServicesInfo, useSecretsInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Shield,
  Plus,
  Trash2,
  CheckCircle,
  Loader2,
  Settings,
  Info,
  Key,
} from 'lucide-react';

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

interface TlsConfig {
  id: string;
  hosts: string[];
  secretName: string;
}

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

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

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

  const availableSecrets = secrets.filter(
    (secret) => secret.namespace === selectedNamespace && secret.type === 'kubernetes.io/tls'
  );

  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 addTlsConfig = () => {
    const newTlsConfig: TlsConfig = {
      id: Date.now().toString(),
      hosts: [''],
      secretName: '',
    };
    setTlsConfigs([...tlsConfigs, newTlsConfig]);
  };

  const removeTlsConfig = (tlsId: string) => {
    if (tlsConfigs.length > 1) {
      setTlsConfigs(tlsConfigs.filter((tls) => tls.id !== tlsId));
    }
  };

  const updateTlsConfig = (tlsId: string, updates: Partial<TlsConfig>) => {
    setTlsConfigs(tlsConfigs.map((tls) => 
      tls.id === tlsId ? { ...tls, ...updates } : tls
    ));
  };

  const updateTlsHost = (tlsId: string, hostIndex: number, host: string) => {
    const tls = tlsConfigs.find(t => t.id === tlsId);
    if (tls) {
      const newHosts = [...tls.hosts];
      newHosts[hostIndex] = host;
      updateTlsConfig(tlsId, { hosts: newHosts });
    }
  };

  const addTlsHost = (tlsId: string) => {
    const tls = tlsConfigs.find(t => t.id === tlsId);
    if (tls) {
      updateTlsConfig(tlsId, { hosts: [...tls.hosts, ''] });
    }
  };

  const removeTlsHost = (tlsId: string, hostIndex: number) => {
    const tls = tlsConfigs.find(t => t.id === tlsId);
    if (tls && tls.hosts.length > 1) {
      const newHosts = tls.hosts.filter((_, index) => index !== hostIndex);
      updateTlsConfig(tlsId, { hosts: newHosts });
    }
  };

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

    // Validate TLS configs
    for (const tls of tlsConfigs) {
      if (!tls.secretName) {
        showToast({
          title: 'Erro de Validação',
          description: 'Secret TLS é obrigatório para todas as configurações TLS',
          variant: 'destructive',
        });
        return false;
      }

      const validHosts = tls.hosts.filter(host => host.trim());
      if (validHosts.length === 0) {
        showToast({
          title: 'Erro de Validação',
          description: 'Pelo menos um host é obrigatório para cada configuração TLS',
          variant: 'destructive',
        });
        return false;
      }
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Build annotations
      const annotations: Record<string, string> = {};
      
      if (ingressClass === 'nginx') {
        annotations['kubernetes.io/ingress.class'] = 'nginx';
        if (enableSslRedirect) {
          annotations['nginx.ingress.kubernetes.io/ssl-redirect'] = 'true';
          annotations['nginx.ingress.kubernetes.io/force-ssl-redirect'] = 'true';
        }
      } else if (ingressClass === 'traefik') {
        annotations['kubernetes.io/ingress.class'] = 'traefik';
        if (enableSslRedirect) {
          annotations['traefik.ingress.kubernetes.io/redirect-entry-point'] = 'https';
        }
      }

      // Create temporary file with the spec
      const tempFileName = `/tmp/ingress-tls-${ingressName}-${Date.now()}.yaml`;
      const yamlContent = `apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${ingressName}
  namespace: ${selectedNamespace}${Object.keys(annotations).length > 0 ? `
  annotations:${Object.entries(annotations).map(([key, value]) => `
    ${key}: "${value}"`).join('')}` : ''}
spec:${ingressClass ? `
  ingressClassName: ${ingressClass}` : ''}
  tls:${tlsConfigs.map((tls) => `
  - hosts:${tls.hosts.filter(h => h.trim()).map(host => `
    - ${host}`).join('')}
    secretName: ${tls.secretName}`).join('')}
  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('')}`;

      const writeCommand = `cat > "${tempFileName}" << 'EOF'
${yamlContent}
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 TLS Criado com Sucesso',
          description: `Ingress "${ingressName}" foi criado com TLS 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">
              <Shield className="h-8 w-8 mr-3 text-green-600" />
              Criar Ingress com TLS
            </h1>
            <p className="text-muted-foreground">
              Configure um Ingress HTTPS com certificados TLS existentes
            </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-tls"
                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</Label>
              <Select
                value={ingressClass}
                onValueChange={setIngressClass}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione a classe" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="nginx">NGINX</SelectItem>
                  <SelectItem value="traefik">Traefik</SelectItem>
                  <SelectItem value="other">Outro</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <Checkbox
              id="sslRedirect"
              checked={enableSslRedirect}
              onCheckedChange={setEnableSslRedirect}
            />
            <Label htmlFor="sslRedirect">
              Habilitar redirecionamento automático HTTP → HTTPS
            </Label>
          </div>
        </CardContent>
      </Card>

      {/* TLS Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Key className="h-5 w-5 mr-2" />
              Configuração TLS
            </div>
            <Button onClick={addTlsConfig} size="sm">
              <Plus className="h-4 w-4 mr-2" />
              Adicionar TLS
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {tlsConfigs.map((tls, index) => (
            <Card key={tls.id} className="border-green-200">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <h4 className="font-medium">Configuração TLS {index + 1}</h4>
                  {tlsConfigs.length > 1 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeTlsConfig(tls.id)}
                      className="text-red-600 hover:text-red-800"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <Label>Secret TLS</Label>
                  <Select
                    value={tls.secretName}
                    onValueChange={(value) => updateTlsConfig(tls.id, { secretName: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Selecione o secret TLS" />
                    </SelectTrigger>
                    <SelectContent>
                      {availableSecrets.map((secret) => (
                        <SelectItem key={secret.name} value={secret.name}>
                          {secret.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {availableSecrets.length === 0 && (
                    <p className="text-xs text-red-600 mt-1">
                      Nenhum secret TLS encontrado neste namespace
                    </p>
                  )}
                </div>
                
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <Label>Hosts</Label>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => addTlsHost(tls.id)}
                    >
                      <Plus className="h-3 w-3 mr-1" />
                      Host
                    </Button>
                  </div>
                  {tls.hosts.map((host, hostIndex) => (
                    <div key={hostIndex} className="flex items-center space-x-2 mb-2">
                      <Input
                        placeholder="ex: app.exemplo.com"
                        value={host}
                        onChange={(e) => updateTlsHost(tls.id, hostIndex, e.target.value)}
                      />
                      {tls.hosts.length > 1 && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removeTlsHost(tls.id, hostIndex)}
                          className="text-red-600"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </CardContent>
      </Card>

      {/* Rules */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Shield 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</Label>
                    <Input
                      placeholder="ex: app.exemplo.com"
                      value={rule.host}
                      onChange={(e) => updateRule(rule.id, { host: e.target.value })}
                    />
                  </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) || tlsConfigs.some(t => !t.secretName)}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Ingress TLS
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default IngressCreateTlsPage;