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 {
  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,
  User,
  Key,
  CheckCircle,
  Loader2,
  FileText,
  Eye,
  EyeOff,
  UserCheck,
  Shield,
} from 'lucide-react';

function SecretCreateBasicAuthPage() {
  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 [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = 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 (!username.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nome de usuário é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

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

    return true;
  };

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

    setCreating(true);
    try {
      const command = `kubectl create secret generic "${secretName}" --from-literal=username="${username}" --from-literal=password="${password}" -n "${selectedNamespace}"`;

      const result = await executeCommand(command);

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

        navigate('/storage/secrets');
      } else {
        showToast({
          title: 'Erro ao Criar Secret Basic Auth',
          description: result.error || 'Falha ao criar a Secret Basic Auth',
          variant: 'destructive',
        });
      }
    } catch (error) {
      const errorMsg =
        error instanceof Error ? error.message : 'Erro inesperado';
      showToast({
        title: 'Erro',
        description: errorMsg,
        variant: 'destructive',
      });
    } finally {
      setCreating(false);
    }
  };

  const generateRandomPassword = () => {
    const chars =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let result = '';
    for (let i = 0; i < 16; i += 1) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setPassword(result);
    showToast({
      title: 'Senha Gerada',
      description: 'Senha segura de 16 caracteres foi gerada',
      variant: 'success',
    });
  };

  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">
              <UserCheck className="h-8 w-8 mr-3 text-yellow-600" />
              Criar Basic Authentication Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret para autenticação básica HTTP (usuário/senha)
            </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: api-basic-auth"
                  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>

        {/* Credentials */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Shield className="h-5 w-5 mr-2" />
              Credenciais
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="username">Nome de Usuário</Label>
                <div className="relative">
                  <User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                  <Input
                    id="username"
                    placeholder="ex: admin"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="pl-10"
                    autoComplete="username"
                  />
                </div>
              </div>
              <div>
                <Label htmlFor="password">Senha</Label>
                <div className="relative">
                  <Key className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                  <Input
                    id="password"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="Digite a senha"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pl-10 pr-20"
                    autoComplete="current-password"
                  />
                  <div className="absolute right-1 top-1 flex items-center space-x-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="h-8 w-8 p-0"
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      type="button"
                      onClick={generateRandomPassword}
                      className="h-8 px-2 text-xs"
                    >
                      Gerar
                    </Button>
                  </div>
                </div>
                <p className="text-sm text-muted-foreground mt-1">
                  Use uma senha forte ou clique em &quot;Gerar&quot; para uma
                  senha aleatória
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Auth Preview */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Key className="h-5 w-5 mr-2" />
              Preview da Autenticação
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center space-x-2">
                <span className="text-sm text-muted-foreground">
                  HTTP Header:
                </span>
                <code className="bg-gray-100 px-2 py-1 rounded text-sm">
                  Authorization: Basic{' '}
                  {username && password
                    ? btoa(`${username}:${password}`)
                    : '[base64-encoded-credentials]'}
                </code>
              </div>
              <div className="flex items-center space-x-2">
                <span className="text-sm text-muted-foreground">
                  Secret Keys:
                </span>
                <div className="flex space-x-2">
                  <code className="bg-gray-100 px-2 py-1 rounded text-sm">
                    username
                  </code>
                  <code className="bg-gray-100 px-2 py-1 rounded text-sm">
                    password
                  </code>
                </div>
              </div>
            </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 Basic Auth
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default SecretCreateBasicAuthPage;
