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,
  CheckCircle,
  Loader2,
  FileText,
  GitBranch,
  Terminal,
  Upload,
} from 'lucide-react';

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

  const [secretName, setSecretName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [sshPrivateKey, setSshPrivateKey] = useState('');
  const [sshPublicKey, setSshPublicKey] = useState('');
  const [sshHost, setSshHost] = useState('');
  const [creating, setCreating] = useState(false);

  const gitHosts = [
    { name: 'GitHub', host: 'github.com' },
    { name: 'GitLab', host: 'gitlab.com' },
    { name: 'Bitbucket', host: 'bitbucket.org' },
    { name: 'Azure DevOps', host: 'ssh.dev.azure.com' },
    { name: 'SourceForge', host: 'git.code.sf.net' },
  ];

  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 (!sshPrivateKey.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Chave privada SSH é obrigatória',
        variant: 'destructive',
      });
      return false;
    }

    // Validar formato da chave privada
    if (
      !sshPrivateKey.includes('-----BEGIN') ||
      !sshPrivateKey.includes('PRIVATE KEY-----')
    ) {
      showToast({
        title: 'Erro de Validação',
        description:
          'Formato da chave privada SSH inválido. Deve começar com "-----BEGIN" e conter "PRIVATE KEY"',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const tempPrivateKeyFile = '/tmp/ssh-privatekey';
      const tempPublicKeyFile = '/tmp/ssh-publickey';
      const tempKnownHostsFile = '/tmp/ssh-known_hosts';

      // Escrever chave privada
      await executeCommand(
        `echo "${sshPrivateKey.replace(/"/g, '\\"')}" > "${tempPrivateKeyFile}"`,
      );

      // Construir comando base
      let command = `kubectl create secret generic "${secretName}" --from-file=ssh-privatekey="${tempPrivateKeyFile}"`;

      // Adicionar chave pública se fornecida
      if (sshPublicKey.trim()) {
        await executeCommand(
          `echo "${sshPublicKey.replace(/"/g, '\\"')}" > "${tempPublicKeyFile}"`,
        );
        command += ` --from-file=ssh-publickey="${tempPublicKeyFile}"`;
      }

      // Adicionar known_hosts se host fornecido
      if (sshHost.trim()) {
        await executeCommand(
          `ssh-keyscan -H "${sshHost}" > "${tempKnownHostsFile}" 2>/dev/null || echo "# Host ${sshHost} not found" > "${tempKnownHostsFile}"`,
        );
        command += ` --from-file=known_hosts="${tempKnownHostsFile}"`;
      }

      command += ` -n "${selectedNamespace}"`;

      const result = await executeCommand(command);

      // Limpar arquivos temporários
      await executeCommand(
        `rm -f "${tempPrivateKeyFile}" "${tempPublicKeyFile}" "${tempKnownHostsFile}"`,
      );

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

        navigate('/storage/secrets');
      } else {
        showToast({
          title: 'Erro ao Criar Secret SSH',
          description: result.error || 'Falha ao criar a Secret SSH',
          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: 'private' | 'public',
  ) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        if (type === 'private') {
          setSshPrivateKey(content);
        } else {
          setSshPublicKey(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">
              <Terminal className="h-8 w-8 mr-3 text-orange-600" />
              Criar SSH Authentication Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret SSH para autenticação em repositórios Git e
              servidores
            </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: git-ssh-credentials"
                  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>

        {/* SSH Host Configuration */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <GitBranch className="h-5 w-5 mr-2" />
              Configuração do Host (Opcional)
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="sshHost">Host SSH</Label>
              <Input
                id="sshHost"
                placeholder="ex: github.com"
                value={sshHost}
                onChange={(e) => setSshHost(e.target.value)}
              />
              <div className="mt-2 text-sm text-muted-foreground">
                Hosts comuns:
                <div className="mt-1 flex flex-wrap gap-2">
                  {gitHosts.map((host) => (
                    <Button
                      key={host.name}
                      variant="outline"
                      size="sm"
                      onClick={() => setSshHost(host.host)}
                      className="h-7 text-xs"
                    >
                      {host.name}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* SSH Keys */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Key className="h-5 w-5 mr-2" />
              Chaves SSH
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Private Key */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="sshPrivateKey">
                  Chave Privada SSH (Obrigatória)
                </Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept=".pem,.key"
                    onChange={(e) => handleFileUpload(e, 'private')}
                    style={{ display: 'none' }}
                    id="private-key-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('private-key-input')?.click()
                    }
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                </div>
              </div>
              <Textarea
                id="sshPrivateKey"
                placeholder="-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn...
-----END OPENSSH PRIVATE KEY-----"
                value={sshPrivateKey}
                onChange={(e) => setSshPrivateKey(e.target.value)}
                rows={8}
                className="font-mono text-sm"
              />
              <p className="text-sm text-muted-foreground mt-1">
                Cole a chave privada SSH (formatos: OpenSSH, RSA, ECDSA,
                Ed25519) ou carregue um arquivo .pem/.key
              </p>
            </div>

            {/* Public Key */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="sshPublicKey">
                  Chave Pública SSH (Opcional)
                </Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept=".pub"
                    onChange={(e) => handleFileUpload(e, 'public')}
                    style={{ display: 'none' }}
                    id="public-key-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('public-key-input')?.click()
                    }
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                </div>
              </div>
              <Textarea
                id="sshPublicKey"
                placeholder="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC... user@hostname"
                value={sshPublicKey}
                onChange={(e) => setSshPublicKey(e.target.value)}
                rows={3}
                className="font-mono text-sm"
              />
              <p className="text-sm text-muted-foreground mt-1">
                Cole a chave pública SSH correspondente (opcional, mas
                recomendado) ou carregue um arquivo .pub
              </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 SSH
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default SecretCreateSSHPage;
