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,
  Plus,
  Trash2,
  Eye,
  EyeOff,
  AlertCircle,
  CheckCircle,
  Loader2,
  Copy,
  FileText,
  Shield,
} from 'lucide-react';

interface KeyValuePair {
  key: string;
  value: string;
  showValue: boolean;
}

export function SecretCreateGenericPage() {
  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 [keyValuePairs, setKeyValuePairs] = useState<KeyValuePair[]>([
    { key: '', value: '', showValue: false },
  ]);
  const [labels, setLabels] = useState<KeyValuePair[]>([
    { key: '', value: '', showValue: true },
  ]);
  const [creating, setCreating] = useState(false);

  const addKeyValuePair = () => {
    setKeyValuePairs([
      ...keyValuePairs,
      { key: '', value: '', showValue: false },
    ]);
  };

  const removeKeyValuePair = (index: number) => {
    if (keyValuePairs.length > 1) {
      setKeyValuePairs(keyValuePairs.filter((_, i) => i !== index));
    }
  };

  const updateKeyValuePair = (
    index: number,
    field: 'key' | 'value',
    value: string,
  ) => {
    const updated = [...keyValuePairs];
    updated[index][field] = value;
    setKeyValuePairs(updated);
  };

  const toggleShowValue = (index: number) => {
    const updated = [...keyValuePairs];
    updated[index].showValue = !updated[index].showValue;
    setKeyValuePairs(updated);
  };

  const addLabel = () => {
    setLabels([...labels, { key: '', value: '', showValue: true }]);
  };

  const removeLabel = (index: number) => {
    if (labels.length > 1) {
      setLabels(labels.filter((_, i) => i !== index));
    }
  };

  const updateLabel = (
    index: number,
    field: 'key' | 'value',
    value: string,
  ) => {
    const updated = [...labels];
    updated[index][field] = value;
    setLabels(updated);
  };

  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;
    }

    const hasValidData = keyValuePairs.some(
      (pair) => pair.key.trim() && pair.value.trim(),
    );
    if (!hasValidData) {
      showToast({
        title: 'Erro de Validação',
        description: 'Pelo menos um par chave/valor é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Construir o comando kubectl
      const validPairs = keyValuePairs.filter(
        (pair) => pair.key.trim() && pair.value.trim(),
      );
      const dataArgs = validPairs
        .map((pair) => `--from-literal="${pair.key}=${pair.value}"`)
        .join(' ');

      const validLabels = labels.filter(
        (label) => label.key.trim() && label.value.trim(),
      );
      const labelArgs =
        validLabels.length > 0
          ? validLabels.map((label) => `${label.key}=${label.value}`).join(' ')
          : '';

      let command = `kubectl create secret generic "${secretName}" ${dataArgs} -n "${selectedNamespace}"`;

      if (labelArgs) {
        // Criar a secret primeiro, depois aplicar os labels
        command += ` && kubectl label secret "${secretName}" ${labelArgs} -n "${selectedNamespace}"`;
      }

      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">
              <Key className="h-8 w-8 mr-3 text-blue-600" />
              Criar Generic Secret
            </h1>
            <p className="text-muted-foreground">
              Crie uma Secret genérica para armazenar dados arbitrários
            </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-api-keys"
                  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>

        {/* Key-Value Pairs */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center">
                <Key className="h-5 w-5 mr-2" />
                Dados da Secret
              </span>
              <Button variant="outline" size="sm" onClick={addKeyValuePair}>
                <Plus className="h-4 w-4 mr-2" />
                Adicionar
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {keyValuePairs.map((pair, index) => (
                <div key={index} className="flex items-center space-x-2">
                  <div className="flex-1">
                    <Input
                      placeholder="Chave (ex: API_KEY)"
                      value={pair.key}
                      onChange={(e) =>
                        updateKeyValuePair(index, 'key', e.target.value)
                      }
                    />
                  </div>
                  <div className="flex-1 relative">
                    <Input
                      type={pair.showValue ? 'text' : 'password'}
                      placeholder="Valor"
                      value={pair.value}
                      onChange={(e) =>
                        updateKeyValuePair(index, 'value', e.target.value)
                      }
                    />
                    <Button
                      variant="ghost"
                      size="sm"
                      className="absolute right-1 top-1 h-8 w-8 p-0"
                      onClick={() => toggleShowValue(index)}
                    >
                      {pair.showValue ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => removeKeyValuePair(index)}
                    disabled={keyValuePairs.length === 1}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Labels */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center">
                <Shield className="h-5 w-5 mr-2" />
                Labels (Opcional)
              </span>
              <Button variant="outline" size="sm" onClick={addLabel}>
                <Plus className="h-4 w-4 mr-2" />
                Adicionar
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {labels.map((label, index) => (
                <div key={index} className="flex items-center space-x-2">
                  <div className="flex-1">
                    <Input
                      placeholder="Chave (ex: app)"
                      value={label.key}
                      onChange={(e) =>
                        updateLabel(index, 'key', e.target.value)
                      }
                    />
                  </div>
                  <div className="flex-1">
                    <Input
                      placeholder="Valor (ex: my-app)"
                      value={label.value}
                      onChange={(e) =>
                        updateLabel(index, 'value', e.target.value)
                      }
                    />
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => removeLabel(index)}
                    disabled={labels.length === 1}
                  >
                    <Trash2 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>
  );
}
