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,
  Map,
  Plus,
  Trash2,
  CheckCircle,
  Loader2,
  FileText,
  Settings,
} from 'lucide-react';

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

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

  const [configMapName, setConfigMapName] = 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: '' },
  ]);
  const [labels, setLabels] = useState<KeyValuePair[]>([
    { key: '', value: '' },
  ]);
  const [creating, setCreating] = useState(false);

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

  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 addLabel = () => {
    setLabels([...labels, { key: '', value: '' }]);
  };

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

    if (!selectedNamespace) {
      showToast({
        title: 'Erro de Validação',
        description: 'Namespace é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    // Verificar se há pelo menos um par chave-valor com dados
    const validPairs = keyValuePairs.filter(
      (pair) => pair.key.trim() && pair.value.trim(),
    );
    if (validPairs.length === 0) {
      showToast({
        title: 'Erro de Validação',
        description: 'Pelo menos um par chave-valor é obrigatório',
        variant: 'destructive',
      });
      return false;
    }

    // Verificar se não há chaves duplicadas
    const keys = validPairs.map((pair) => pair.key.trim());
    const uniqueKeys = new Set(keys);
    if (keys.length !== uniqueKeys.size) {
      showToast({
        title: 'Erro de Validação',
        description: 'Chaves duplicadas não são permitidas',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      // Construir comando kubectl
      let command = `kubectl create configmap "${configMapName}" -n "${selectedNamespace}"`;

      // Adicionar dados
      const validPairs = keyValuePairs.filter(
        (pair) => pair.key.trim() && pair.value.trim(),
      );
      validPairs.forEach((pair) => {
        command += ` --from-literal="${pair.key.trim()}"="${pair.value.trim()}"`;
      });

      const result = await executeCommand(command);

      if (result.success) {
        // Adicionar labels se houver (comando separado)
        const validLabels = labels.filter(
          (label) => label.key.trim() && label.value.trim(),
        );
        if (validLabels.length > 0) {
          const labelString = validLabels
            .map((label) => `${label.key.trim()}=${label.value.trim()}`)
            .join(' ');
          const labelCommand = `kubectl label configmap "${configMapName}" ${labelString} -n "${selectedNamespace}"`;
          const labelResult = await executeCommand(labelCommand);

          if (!labelResult.success) {
            showToast({
              title: 'ConfigMap Criado com Aviso',
              description: `ConfigMap "${configMapName}" foi criado, mas falha ao aplicar labels: ${labelResult.error}`,
              variant: 'destructive',
            });
            navigate('/storage/configmaps');
            return;
          }
        }

        showToast({
          title: 'ConfigMap Criado com Sucesso',
          description: `ConfigMap "${configMapName}" foi criado no namespace "${selectedNamespace}"`,
          variant: 'success',
        });

        // Redirecionar para a página de configmaps
        navigate('/storage/configmaps');
      } else {
        showToast({
          title: 'Erro ao Criar ConfigMap',
          description: result.error || 'Falha ao criar o ConfigMap',
          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">
              <Map className="h-8 w-8 mr-3 text-blue-600" />
              Criar ConfigMap
            </h1>
            <p className="text-muted-foreground">
              Crie um ConfigMap para armazenar dados de configuração
            </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="configMapName">Nome do ConfigMap</Label>
                <Input
                  id="configMapName"
                  placeholder="ex: my-app-config"
                  value={configMapName}
                  onChange={(e) => setConfigMapName(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>

        {/* Data */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center">
                <Settings className="h-5 w-5 mr-2" />
                Dados de Configuração
              </div>
              <Button variant="outline" size="sm" onClick={addKeyValuePair}>
                <Plus className="h-4 w-4 mr-2" />
                Adicionar
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {keyValuePairs.map((pair, index) => (
              <div
                key={`pair-${index}`}
                className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg"
              >
                <div>
                  <Label htmlFor={`key-${index}`}>Chave</Label>
                  <Input
                    id={`key-${index}`}
                    placeholder="ex: database.host"
                    value={pair.key}
                    onChange={(e) =>
                      updateKeyValuePair(index, 'key', e.target.value)
                    }
                  />
                </div>
                <div>
                  <Label htmlFor={`value-${index}`}>Valor</Label>
                  <div className="flex items-center space-x-2">
                    <Textarea
                      id={`value-${index}`}
                      placeholder="ex: localhost:5432"
                      value={pair.value}
                      onChange={(e) =>
                        updateKeyValuePair(index, 'value', e.target.value)
                      }
                      rows={3}
                    />
                    {keyValuePairs.length > 1 && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => removeKeyValuePair(index)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>

        {/* Labels */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center">
                <FileText className="h-5 w-5 mr-2" />
                Labels (Opcional)
              </div>
              <Button variant="outline" size="sm" onClick={addLabel}>
                <Plus className="h-4 w-4 mr-2" />
                Adicionar
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {labels.map((label, index) => (
              <div
                key={`label-${index}`}
                className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg"
              >
                <div>
                  <Label htmlFor={`label-key-${index}`}>Chave</Label>
                  <Input
                    id={`label-key-${index}`}
                    placeholder="ex: app"
                    value={label.key}
                    onChange={(e) => updateLabel(index, 'key', e.target.value)}
                  />
                </div>
                <div>
                  <Label htmlFor={`label-value-${index}`}>Valor</Label>
                  <div className="flex items-center space-x-2">
                    <Input
                      id={`label-value-${index}`}
                      placeholder="ex: my-app"
                      value={label.value}
                      onChange={(e) =>
                        updateLabel(index, 'value', e.target.value)
                      }
                    />
                    {labels.length > 1 && (
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => removeLabel(index)}
                        className="text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    )}
                  </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={handleCreateConfigMap} disabled={creating}>
          {creating ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando...
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4 mr-2" />
              Criar ConfigMap
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default ConfigMapCreatePage;
