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,
  Settings,
  Shield,
  Upload,
  Eye,
  EyeOff,
  Server,
} from 'lucide-react';

function SecretCreateServiceAccountPage() {
  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 [token, setToken] = useState('');
  const [caCert, setCaCert] = useState('');
  const [showToken, setShowToken] = useState(false);
  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 (!token.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Token do Service Account é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const tempTokenFile = '/tmp/sa-token';
      const tempCaCertFile = '/tmp/sa-ca.crt';

      // Escrever token
      await executeCommand(
        `echo "${token.replace(/"/g, '\\"')}" > "${tempTokenFile}"`,
      );

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

      // Adicionar certificado CA se fornecido
      if (caCert.trim()) {
        await executeCommand(
          `echo "${caCert.replace(/"/g, '\\"')}" > "${tempCaCertFile}"`,
        );
        command += ` --from-file=ca.crt="${tempCaCertFile}"`;
      }

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

      const result = await executeCommand(command);

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

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

        navigate('/storage/secrets');
      } else {
        showToast({
          title: 'Erro ao Criar Secret Service Account',
          description:
            result.error || 'Falha ao criar a Secret Service Account',
          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: 'token' | 'ca',
  ) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        if (type === 'token') {
          setToken(content);
        } else {
          setCaCert(content);
        }
      };
      reader.readAsText(file);
    }
  };

  const fetchCurrentServiceAccountToken = async () => {
    try {
      const result = await executeCommand(
        `kubectl get secrets -o jsonpath='{.items[?(@.type=="kubernetes.io/service-account-token")].data.token}' | head -1 | base64 -d`,
      );

      if (result.success && result.stdout) {
        setToken(result.stdout.trim());
        showToast({
          title: 'Token Obtido',
          description: 'Token do Service Account atual foi carregado',
          variant: 'success',
        });
      } else {
        showToast({
          title: 'Token Não Encontrado',
          description: 'Não foi possível obter o token automaticamente',
          variant: 'destructive',
        });
      }
    } catch {
      showToast({
        title: 'Erro ao Obter Token',
        description: 'Falha ao executar comando kubectl',
        variant: 'destructive',
      });
    }
  };

  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">
              <Settings className="h-8 w-8 mr-3 text-indigo-600" />
              Criar Service Account Token Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret com token para acessar APIs do Kubernetes
            </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: service-account-token"
                  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>

        {/* Token */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center">
                <Key className="h-5 w-5 mr-2" />
                Token do Service Account
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={fetchCurrentServiceAccountToken}
                disabled={creating}
              >
                <Server className="h-4 w-4 mr-2" />
                Obter Token Atual
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="token">Token (Obrigatório)</Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept="*"
                    onChange={(e) => handleFileUpload(e, 'token')}
                    style={{ display: 'none' }}
                    id="token-file-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('token-file-input')?.click()
                    }
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowToken(!showToken)}
                  >
                    {showToken ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </Button>
                </div>
              </div>
              <Textarea
                id="token"
                placeholder="eyJhbGciOiJSUzI1NiIsImtpZCI6IjVkNmY3YzhhLTQ5NjUtNGQ4Yi1iZDFkLWVhMjIzNGNkMjYwNyJ9..."
                value={token}
                onChange={(e) => setToken(e.target.value)}
                rows={6}
                className={`font-mono text-sm ${!showToken ? 'text-security-disc' : ''}`}
                style={
                  !showToken
                    ? { textSecurity: 'disc', WebkitTextSecurity: 'disc' }
                    : {}
                }
              />
              <p className="text-sm text-muted-foreground mt-1">
                Token JWT do Service Account para autenticação na API do
                Kubernetes
              </p>
            </div>
          </CardContent>
        </Card>

        {/* CA Certificate */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Shield className="h-5 w-5 mr-2" />
              Certificado CA (Opcional)
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="caCert">Certificado CA (ca.crt)</Label>
                <div className="flex items-center space-x-2">
                  <input
                    type="file"
                    accept=".crt,.pem,.cert"
                    onChange={(e) => handleFileUpload(e, 'ca')}
                    style={{ display: 'none' }}
                    id="ca-file-input"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      document.getElementById('ca-file-input')?.click()
                    }
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Carregar Arquivo
                  </Button>
                </div>
              </div>
              <Textarea
                id="caCert"
                placeholder="-----BEGIN CERTIFICATE-----
MIIDBTCCAe2gAwIBAgIJAK+7kbPGkjgfMA0GCSqGSIb3DQEBCwUAMBkxFzAVBgNV...
-----END CERTIFICATE-----"
                value={caCert}
                onChange={(e) => setCaCert(e.target.value)}
                rows={6}
                className="font-mono text-sm"
              />
              <p className="text-sm text-muted-foreground mt-1">
                Certificado CA do cluster Kubernetes (opcional, mas recomendado)
              </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 Service Account
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default SecretCreateServiceAccountPage;
