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 { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/useToast';
import { useKubectl, useNamespacesInfo, useServicesInfo } from '@/hooks/useKubectl';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import {
  ArrowLeft,
  Zap,
  CheckCircle,
  Loader2,
  Settings,
  Info,
  Key,
  Globe,
  Eye,
  EyeOff,
  Server,
} from 'lucide-react';

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

  const [appName, setAppName] = useState('');
  const [domain, setDomain] = useState('');
  const [email, setEmail] = useState('gouveiaeu@gmail.com');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [serviceName, setServiceName] = useState('');
  const [servicePort, setServicePort] = useState(80);
  const [path, setPath] = useState('/');
  const [pathType, setPathType] = useState<'Prefix' | 'Exact' | 'ImplementationSpecific'>('Prefix');
  const [createIssuer, setCreateIssuer] = useState(true);
  const [issuerName, setIssuerName] = useState('letsencrypt');
  const [enableAdvancedSettings, setEnableAdvancedSettings] = useState(true);
  const [proxyBodySize, setProxyBodySize] = useState('300m');
  const [proxyTimeout, setProxyTimeout] = useState('1800');
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);

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

  const validateForm = () => {
    if (!appName.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome da aplicação é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!domain.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Domínio é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!email.trim() || !email.includes('@')) {
      showToast({
        title: 'Erro de Validação',
        description: 'Email válido é obrigatório para Let\'s Encrypt',
        variant: 'destructive',
      });
      return false;
    }

    if (!serviceName) {
      showToast({
        title: 'Erro de Validação',
        description: 'Serviço de backend é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    if (!servicePort || 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 generateYamlManifests = () => {
    const manifests = [];

    // Issuer (if enabled)
    if (createIssuer) {
      manifests.push(`apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: ${issuerName}
  namespace: ${selectedNamespace}
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: ${email}
    privateKeySecretRef:
      name: account-key
    solvers:
    - http01:
       ingress:
         class: nginx`);
    }

    // Certificate
    manifests.push(`apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: ${appName}
  namespace: ${selectedNamespace}
spec:
  secretName: ${appName}-certificate
  issuerRef:
    name: ${issuerName}
  dnsNames:
  - ${domain}`);

    // Build annotations
    const annotations = [
      'kubernetes.io/ingress.class: "nginx"',
      'nginx.ingress.kubernetes.io/ssl-redirect: "true"',
      'nginx.ingress.kubernetes.io/force-ssl-redirect: "true"',
      `cert-manager.io/issuer: "${issuerName}"`,
    ];

    if (enableAdvancedSettings) {
      annotations.push(
        'nginx.ingress.kubernetes.io/affinity: "cookie"',
        `nginx.ingress.kubernetes.io/proxy-body-size: "${proxyBodySize}"`,
        `nginx.ingress.kubernetes.io/proxy-connect-timeout: "${proxyTimeout}"`,
        `nginx.ingress.kubernetes.io/proxy-next-upstream-timeout: "${proxyTimeout}"`,
        `nginx.ingress.kubernetes.io/proxy-read-timeout: "${proxyTimeout}"`,
        `nginx.ingress.kubernetes.io/proxy-send-timeout: "${proxyTimeout}"`,
        'nginx.ingress.kubernetes.io/session-cookie-hash: "sha1"'
      );
    }

    // Ingress
    manifests.push(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${appName}
  namespace: ${selectedNamespace}
  annotations:
    ${annotations.join('\n    ')}
spec:
  tls:
  - hosts:
      - ${domain}
    secretName: ${appName}-certificate
  rules:
  - host: ${domain}
    http:
      paths:
      - pathType: ${pathType}
        path: "${path}"
        backend:
          service:
            name: ${serviceName}
            port:
              number: ${servicePort}`);

    return manifests.join('\n---\n');
  };

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

    setCreating(true);
    try {
      const yamlContent = generateYamlManifests();
      
      // Create temporary file with the manifests
      const tempFileName = `/tmp/ingress-letsencrypt-nginx-${appName}-${Date.now()}.yaml`;
      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 manifests
      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 NGINX + Let\'s Encrypt Criado',
          description: `Ingress "${appName}" com certificado automático foi criado. O certificado será emitido em alguns minutos.`,
          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">
              <Zap className="h-8 w-8 mr-3 text-orange-600" />
              Let's Encrypt + NGINX
            </h1>
            <p className="text-muted-foreground">
              Configure HTTPS automático com NGINX Ingress Controller
            </p>
          </div>
        </div>
      </div>

      {/* Application Info */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Globe className="h-5 w-5 mr-2" />
            Informações da Aplicação
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="appName">Nome da Aplicação</Label>
              <Input
                id="appName"
                placeholder="ex: api, app, blog"
                value={appName}
                onChange={(e) => setAppName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Usado para gerar o nome do Ingress e Certificate
              </p>
            </div>
            <div>
              <Label htmlFor="domain">Domínio Completo</Label>
              <Input
                id="domain"
                placeholder="ex: app.exemplo.com, api.meusite.com.br"
                value={domain}
                onChange={(e) => setDomain(e.target.value.toLowerCase())}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Domínio completo da aplicação
              </p>
            </div>
          </div>

          {domain && (
            <div className="p-3 bg-blue-50 rounded-md border border-blue-200">
              <p className="text-sm font-medium text-blue-800">
                URL Final: <span className="font-mono">https://{domain}</span>
              </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>
        </CardContent>
      </Card>

      {/* Let's Encrypt Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Key className="h-5 w-5 mr-2" />
            Configuração Let's Encrypt
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="email">Email para Let's Encrypt</Label>
            <Input
              id="email"
              type="email"
              placeholder="seu@email.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Usado para notificações sobre expiração de certificado
            </p>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="createIssuer"
              checked={createIssuer}
              onCheckedChange={setCreateIssuer}
            />
            <Label htmlFor="createIssuer">
              Criar Issuer (recomendado se não existir no namespace)
            </Label>
          </div>

          <div>
            <Label htmlFor="issuerName">Nome do Issuer</Label>
            <Input
              id="issuerName"
              placeholder="letsencrypt"
              value={issuerName}
              onChange={(e) => setIssuerName(e.target.value)}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Issuer é específico do namespace (diferente do ClusterIssuer)
            </p>
          </div>
        </CardContent>
      </Card>

      {/* Service Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Server className="h-5 w-5 mr-2" />
            Configuração do Serviço Backend
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="serviceName">Serviço</Label>
              <Select
                value={serviceName}
                onValueChange={setServiceName}
              >
                <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 htmlFor="servicePort">Porta do Serviço</Label>
              <Input
                id="servicePort"
                type="number"
                placeholder="80"
                value={servicePort}
                onChange={(e) => setServicePort(parseInt(e.target.value) || 0)}
              />
            </div>
            <div>
              <Label htmlFor="pathType">Tipo do Path</Label>
              <Select
                value={pathType}
                onValueChange={(value) => setPathType(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>

          <div>
            <Label htmlFor="path">Path</Label>
            <Input
              id="path"
              placeholder="/"
              value={path}
              onChange={(e) => setPath(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Advanced NGINX Settings */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Settings className="h-5 w-5 mr-2" />
              Configurações Avançadas NGINX
            </div>
            <Checkbox
              id="enableAdvancedSettings"
              checked={enableAdvancedSettings}
              onCheckedChange={setEnableAdvancedSettings}
            />
          </CardTitle>
        </CardHeader>
        {enableAdvancedSettings && (
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="proxyBodySize">Tamanho Máximo do Body</Label>
                <Input
                  id="proxyBodySize"
                  placeholder="300m"
                  value={proxyBodySize}
                  onChange={(e) => setProxyBodySize(e.target.value)}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Ex: 300m, 1g para uploads grandes
                </p>
              </div>
              <div>
                <Label htmlFor="proxyTimeout">Timeout (segundos)</Label>
                <Input
                  id="proxyTimeout"
                  placeholder="1800"
                  value={proxyTimeout}
                  onChange={(e) => setProxyTimeout(e.target.value)}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Timeout para conexões longas
                </p>
              </div>
            </div>
            
            <div className="p-3 bg-gray-50 rounded-md">
              <p className="text-sm text-gray-600">
                <strong>Configurações incluídas:</strong> SSL redirect, session affinity, 
                timeouts personalizados, e hash de cookie SHA1
              </p>
            </div>
          </CardContent>
        )}
      </Card>

      {/* Preview */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <Eye className="h-5 w-5 mr-2" />
              Pré-visualização dos Manifestos
            </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'}
            </Button>
          </CardTitle>
        </CardHeader>
        {showPreview && (
          <CardContent>
            <Textarea
              value={generateYamlManifests()}
              readOnly
              rows={25}
              className="font-mono text-xs"
            />
          </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 || !appName.trim() || !domain.trim() || !serviceName}
        >
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Ingress + Let's Encrypt
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default IngressCreateLetsEncryptNginxPage;