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

export function SecretCreateDockerRegistryPage() {
  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 [dockerServer, setDockerServer] = useState('');
  const [dockerUsername, setDockerUsername] = useState('');
  const [dockerPassword, setDockerPassword] = useState('');
  const [dockerEmail, setDockerEmail] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [creating, setCreating] = useState(false);

  const registryPresets = [
    { name: 'Docker Hub', server: 'https://index.docker.io/v1/' },
    {
      name: 'Amazon ECR',
      server: 'https://[account-id].dkr.ecr.[region].amazonaws.com',
    },
    { name: 'Google Container Registry', server: 'https://gcr.io' },
    {
      name: 'Microsoft Container Registry',
      server: 'https://[registry-name].azurecr.io',
    },
    { name: 'GitHub Container Registry', server: 'https://ghcr.io' },
    { name: 'Quay.io', server: 'https://quay.io' },
    {
      name: 'Oracle Container Registry',
      server: 'https://[region-key].ocir.io',
    },
    {
      name: 'Huawei Cloud Container Registry',
      server: 'https://[region].hwcr.io',
    },
  ];

  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 (!dockerServer.trim()) {
      showToast({
        title: 'Erro de Validação',
        description: 'Servidor Docker é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

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

    if (!dockerPassword.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 {
      let command =
        `kubectl create secret docker-registry "${secretName}" ` +
        `--docker-server="${dockerServer}" ` +
        `--docker-username="${dockerUsername}" ` +
        `--docker-password="${dockerPassword}" ` +
        `-n "${selectedNamespace}"`;

      if (dockerEmail.trim()) {
        command += ` --docker-email="${dockerEmail}"`;
      }

      const result = await executeCommand(command);

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

        // Redirecionar para a página de secrets
        navigate('/storage/secrets');
      } else {
        showToast({
          title: 'Erro ao Criar Secret',
          description: result.error || 'Falha ao criar a Secret',
          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">
              <Container className="h-8 w-8 mr-3 text-purple-600" />
              Criar Docker Registry Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret para autenticação em registry Docker privado
            </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-registry-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>

        {/* Registry Configuration */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Globe className="h-5 w-5 mr-2" />
              Configuração do Registry
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="dockerServer">Servidor Docker</Label>
              <Input
                id="dockerServer"
                placeholder="ex: https://index.docker.io/v1/"
                value={dockerServer}
                onChange={(e) => setDockerServer(e.target.value)}
              />
              <div className="mt-2 text-sm text-muted-foreground">
                Presets comuns:
                <div className="mt-1 flex flex-wrap gap-2">
                  {registryPresets.map((preset) => (
                    <Button
                      key={preset.name}
                      variant="outline"
                      size="sm"
                      onClick={() => setDockerServer(preset.server)}
                      className="h-7 text-xs"
                    >
                      {preset.name}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Credentials */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Key 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="dockerUsername">Nome de Usuário</Label>
                <Input
                  id="dockerUsername"
                  placeholder="ex: myusername"
                  value={dockerUsername}
                  onChange={(e) => setDockerUsername(e.target.value)}
                  autoComplete="username"
                />
              </div>
              <div>
                <Label htmlFor="dockerEmail">Email (Opcional)</Label>
                <Input
                  id="dockerEmail"
                  type="email"
                  placeholder="ex: user@example.com"
                  value={dockerEmail}
                  onChange={(e) => setDockerEmail(e.target.value)}
                  autoComplete="email"
                />
              </div>
            </div>
            <div>
              <Label htmlFor="dockerPassword">Senha</Label>
              <div className="relative">
                <Input
                  id="dockerPassword"
                  type={showPassword ? 'text' : 'password'}
                  placeholder="Digite sua senha"
                  value={dockerPassword}
                  onChange={(e) => setDockerPassword(e.target.value)}
                  autoComplete="current-password"
                />
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute right-1 top-1 h-8 w-8 p-0"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </Button>
              </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
            </>
          )}
        </Button>
      </div>
    </div>
  );
}
