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

export function IngressCreateLetsEncryptTraefikPage() {
  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'>('Exact');
  const [createClusterIssuer, setCreateClusterIssuer] = useState(true);
  const [clusterIssuerName, setClusterIssuerName] = useState('letsencrypt');
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);

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

  const fullDomain = `${appName}.${domain}`;

  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 = [];

    // ClusterIssuer (if enabled)
    if (createClusterIssuer) {
      manifests.push(`apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: ${clusterIssuerName}
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: ${email}
    privateKeySecretRef:
      name: ${clusterIssuerName}
    solvers:
      - http01:
          ingress:
            class: traefik`);
    }

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

    // Ingress
    manifests.push(`apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ${appName}
  namespace: ${selectedNamespace}
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  tls:
  - hosts:
    - ${fullDomain}
    secretName: ${appName}-tls-cert
  rules:
  - host: ${fullDomain}
    http:
      paths:
        - path: ${path}
          pathType: ${pathType}
          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-traefik-${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 Let\'s Encrypt Criado com Sucesso',
          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-purple-600" />
              Let's Encrypt + Traefik
            </h1>
            <p className="text-muted-foreground">
              Configure HTTPS automático com certificados gratuitos do Let's Encrypt
            </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 Base</Label>
              <Input
                id="domain"
                placeholder="ex: exemplo.com, meusite.com.br"
                value={domain}
                onChange={(e) => setDomain(e.target.value.toLowerCase())}
              />
            </div>
          </div>

          {appName && 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://{fullDomain}</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="createClusterIssuer"
              checked={createClusterIssuer}
              onCheckedChange={setCreateClusterIssuer}
            />
            <Label htmlFor="createClusterIssuer">
              Criar ClusterIssuer (recomendado se não existir)
            </Label>
          </div>

          <div>
            <Label htmlFor="clusterIssuerName">Nome do ClusterIssuer</Label>
            <Input
              id="clusterIssuerName"
              placeholder="letsencrypt"
              value={clusterIssuerName}
              onChange={(e) => setClusterIssuerName(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Service Configuration */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Settings 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>

      {/* 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={20}
              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 IngressCreateLetsEncryptTraefikPage;