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,
  Key,
  Shield,
  CheckCircle,
  Loader2,
  FileText,
  Lock,
  Plus,
} from 'lucide-react';

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

  const [secretName, setSecretName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    // Se o namespace global é 'all', use 'default', senão use o namespace global
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [tlsCert, setTlsCert] = useState('');
  const [tlsKey, setTlsKey] = useState('');
  const [creating, setCreating] = useState(false);

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

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

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

    if (!tlsKey.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Chave privada TLS é obrigatória',
        variant: 'destructive',
      });
      return false;
    }

    // Validar se os campos não foram invertidos
    if (
      tlsCert.includes('-----BEGIN PRIVATE KEY-----') ||
      tlsCert.includes('-----BEGIN RSA PRIVATE KEY-----')
    ) {
      showToast({
        title: 'Erro de Validação',
        description:
          'Você colocou uma chave privada no campo do certificado. Verifique se os campos não foram invertidos.',
        variant: 'destructive',
      });
      return false;
    }

    if (tlsKey.includes('-----BEGIN CERTIFICATE-----')) {
      showToast({
        title: 'Erro de Validação',
        description:
          'Você colocou um certificado no campo da chave privada. Verifique se os campos não foram invertidos.',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Salvar certificado e chave em arquivos temporários
      const tempCertFile = '/tmp/tls-cert.pem';
      const tempKeyFile = '/tmp/tls-key.pem';

      // Escrever certificado em arquivo temporário
      await executeCommand(
        `echo "${tlsCert.replace(/"/g, '\\"')}" > "${tempCertFile}"`,
      );

      // Escrever chave em arquivo temporário
      await executeCommand(
        `echo "${tlsKey.replace(/"/g, '\\"')}" > "${tempKeyFile}"`,
      );

      // Criar a Secret TLS
      const command = `kubectl create secret tls "${secretName}" --cert="${tempCertFile}" --key="${tempKeyFile}" -n "${selectedNamespace}"`;

      const result = await executeCommand(command);

      // Limpar arquivos temporários
      await executeCommand(`rm -f "${tempCertFile}" "${tempKeyFile}"`);

      if (result.success) {
        showToast({
          title: 'Secret TLS Criada com Sucesso',
          description: `Secret "${secretName}" foi criada no namespace "${selectedNamespace}"`,
          variant: 'success',
        });

        // Redirecionar para a página de secrets
        navigate('/storage/secrets');
      } else {
        let errorMessage = result.error || 'Falha ao criar a Secret TLS';

        // Verificar se é erro de campos invertidos
        if (errorMessage.includes('PEM inputs may have been switched')) {
          errorMessage =
            'Os campos foram invertidos: verifique se o certificado está no campo correto e a chave privada no campo da chave privada.';
        }

        showToast({
          title: 'Erro ao Criar Secret TLS',
          description: errorMessage,
          variant: 'destructive',
        });
      }
    } catch (error) {
      const errorMsg =
        error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  const handleFileUpload = (
    event: React.ChangeEvent<HTMLInputElement>,
    type: 'cert' | 'key',
  ) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        if (type === 'cert') {
          setTlsCert(content);
        } else {
          setTlsKey(content);
        }
      };
      reader.readAsText(file);
    }
  };

  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">
              <Lock className="h-8 w-8 mr-3 text-green-600" />
              Criar TLS Certificate Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret TLS para certificados SSL/TLS e chaves privadas
            </p>
          </div>
        </div>
      </div>

      {/* Form */}
      <div className="space-y-6">
        {/* Basic Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <FileText 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="secretName">Nome da Secret</Label>
                <Input
                  id="secretName"
                  placeholder="ex: my-tls-secret"
                  value={secretName}
                  onChange={(e) => setSecretName(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>
          </CardContent>
        </Card>

        {/* TLS Certificate */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Shield className="h-5 w-5 mr-2" />
              Certificado TLS
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="tlsCert">Certificado (tls.crt)</Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept=".crt,.pem,.cert"
                    onChange={(e) => handleFileUpload(e, 'cert')}
                    style={{ display: 'none' }}
                    id="cert-file-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('cert-file-input')?.click()
                    }
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                </div>
              </div>
              <Textarea
                id="tlsCert"
                placeholder="-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAM+6...
-----END CERTIFICATE-----"
                value={tlsCert}
                onChange={(e) => setTlsCert(e.target.value)}
                rows={8}
                className="font-mono text-sm"
              />
              <p className="text-sm text-muted-foreground mt-1">
                Cole o certificado TLS em formato PEM (deve começar com
                &quot;-----BEGIN CERTIFICATE-----&quot;) ou carregue um arquivo
                .crt/.pem
              </p>
            </div>
          </CardContent>
        </Card>

        {/* TLS Private Key */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Key className="h-5 w-5 mr-2" />
              Chave Privada TLS
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="tlsKey">Chave Privada (tls.key)</Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept=".key,.pem"
                    onChange={(e) => handleFileUpload(e, 'key')}
                    style={{ display: 'none' }}
                    id="key-file-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('key-file-input')?.click()
                    }
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                </div>
              </div>
              <Textarea
                id="tlsKey"
                placeholder="-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...
-----END PRIVATE KEY-----"
                value={tlsKey}
                onChange={(e) => setTlsKey(e.target.value)}
                rows={8}
                className="font-mono text-sm"
              />
              <p className="text-sm text-muted-foreground mt-1">
                Cole a chave privada TLS em formato PEM (deve começar com
                &quot;-----BEGIN PRIVATE KEY-----&quot;) ou carregue um arquivo
                .key/.pem
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 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={handleCreateSecret} disabled={creating}>
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar Secret TLS
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default SecretCreateTLSPage;
