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,
  Database,
  Upload,
  CheckCircle,
  Loader2,
  Settings,
  AlertCircle,
  Eye,
  EyeOff,
} from 'lucide-react';

interface ParsedProperty {
  key: string;
  value: string;
  lineNumber: number;
  isValid: boolean;
  error?: string;
}

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

  const [configMapName, setConfigMapName] = useState('');
  const [selectedNamespace, setSelectedNamespace] = useState(() => {
    return globalNamespace === 'all' ? 'default' : globalNamespace;
  });
  const [propertiesContent, setPropertiesContent] = useState('');
  const [parsedProperties, setParsedProperties] = useState<ParsedProperty[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);

  const parsePropertiesFile = (content: string): ParsedProperty[] => {
    const lines = content.split('\n');
    const properties: ParsedProperty[] = [];

    lines.forEach((line, index) => {
      const trimmedLine = line.trim();

      // Skip empty lines and comments
      if (!trimmedLine || trimmedLine.startsWith('#') || trimmedLine.startsWith('!')) {
        return;
      }

      // Handle line continuation with backslash
      let processedLine = trimmedLine;
      if (processedLine.endsWith('\\')) {
        // For simplicity, we'll remove the backslash and continue on the same line
        processedLine = processedLine.slice(0, -1);
      }

      // Find the separator (= or : or space)
      let separatorIndex = -1;
      let separator = '';

      // Look for = first
      separatorIndex = processedLine.indexOf('=');
      if (separatorIndex !== -1) {
        separator = '=';
      } else {
        // Look for : 
        separatorIndex = processedLine.indexOf(':');
        if (separatorIndex !== -1) {
          separator = ':';
        } else {
          // Look for space
          separatorIndex = processedLine.indexOf(' ');
          if (separatorIndex !== -1) {
            separator = ' ';
          }
        }
      }

      if (separatorIndex === -1) {
        properties.push({
          key: processedLine,
          value: '',
          lineNumber: index + 1,
          isValid: false,
          error: `Formato inválido: faltando separador (=, :, ou espaço)`,
        });
        return;
      }

      const key = processedLine.substring(0, separatorIndex).trim();
      const value = processedLine.substring(separatorIndex + 1).trim();

      if (!key) {
        properties.push({
          key: '',
          value: value,
          lineNumber: index + 1,
          isValid: false,
          error: 'Chave vazia',
        });
        return;
      }

      // Process escape sequences in key and value
      const processedKey = key.replace(/\\(.)/g, '$1');
      const processedValue = value.replace(/\\(.)/g, '$1');

      // Validate key format (Java properties keys can contain dots, but we'll be more restrictive for ConfigMap)
      if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(processedKey)) {
        properties.push({
          key: processedKey,
          value: processedValue,
          lineNumber: index + 1,
          isValid: false,
          error: 'Nome de chave inválido para ConfigMap',
        });
        return;
      }

      properties.push({
        key: processedKey,
        value: processedValue,
        lineNumber: index + 1,
        isValid: true,
      });
    });

    return properties;
  };

  const handleContentChange = (content: string) => {
    setPropertiesContent(content);
    if (content.trim()) {
      const parsed = parsePropertiesFile(content);
      setParsedProperties(parsed);
    } else {
      setParsedProperties([]);
    }
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        handleContentChange(content);
      };
      reader.readAsText(file);
    }
  };

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

    const validProperties = parsedProperties.filter((p) => p.isValid);
    if (validProperties.length === 0) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nenhuma propriedade válida encontrada',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const validProperties = parsedProperties.filter((p) => p.isValid);

      let command = `kubectl create configmap "${configMapName}" -n "${selectedNamespace}"`;

      validProperties.forEach((property) => {
        command += ` --from-literal="${property.key}"="${property.value}"`;
      });

      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'ConfigMap Criado com Sucesso',
          description: `ConfigMap "${configMapName}" foi criado com ${validProperties.length} propriedades`,
          variant: 'success',
        });
        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);
    }
  };

  const validProperties = parsedProperties.filter((p) => p.isValid);
  const invalidProperties = parsedProperties.filter((p) => !p.isValid);

  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">
              <Database className="h-8 w-8 mr-3 text-purple-600" />
              Importar Arquivo .properties
            </h1>
            <p className="text-muted-foreground">
              Importe propriedades Java de um arquivo .properties
            </p>
          </div>
        </div>
      </div>

      {/* Basic Info */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Settings 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: 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>

      {/* File Upload */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Upload className="h-5 w-5 mr-2" />
            Arquivo .properties
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="propertiesFile">Carregar arquivo .properties</Label>
            <input
              type="file"
              accept=".properties,.config"
              onChange={handleFileUpload}
              className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <Label htmlFor="propertiesContent">
              Ou cole o conteúdo do arquivo .properties
            </Label>
            <Textarea
              id="propertiesContent"
              placeholder={`# Exemplo de arquivo .properties
# Configurações do banco de dados
database.host=localhost
database.port=5432
database.name=myapp
database.ssl=true

# Configurações da API
api.url=https://api.example.com
api.timeout=30000
api.retries=3

# Configurações de logging
logging.level=INFO
logging.format=JSON
logging.file=/var/log/app.log

# Configurações de cache
cache.enabled=true
cache.size=1000
cache.ttl=3600`}
              value={propertiesContent}
              onChange={(e) => handleContentChange(e.target.value)}
              rows={12}
              className="font-mono text-sm"
            />
          </div>
        </CardContent>
      </Card>

      {/* Preview */}
      {parsedProperties.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center">
                <Eye className="h-5 w-5 mr-2" />
                Pré-visualização
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowPreview(!showPreview)}
              >
                {showPreview ? (
                  <EyeOff className="h-4 w-4" />
                ) : (
                  <Eye className="h-4 w-4" />
                )}
                {showPreview ? 'Ocultar' : 'Mostrar'}
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-5 w-5 text-green-600" />
                <span className="text-sm font-medium">
                  {validProperties.length} propriedades válidas
                </span>
              </div>
              {invalidProperties.length > 0 && (
                <div className="flex items-center space-x-2">
                  <AlertCircle className="h-5 w-5 text-red-600" />
                  <span className="text-sm font-medium text-red-600">
                    {invalidProperties.length} propriedades inválidas
                  </span>
                </div>
              )}
            </div>

            {showPreview && (
              <div className="space-y-4">
                {validProperties.length > 0 && (
                  <div>
                    <h4 className="font-medium text-green-700 mb-2">
                      Propriedades Válidas:
                    </h4>
                    <div className="bg-green-50 p-3 rounded-md space-y-1 max-h-60 overflow-y-auto">
                      {validProperties.map((property, index) => (
                        <div key={index} className="text-sm font-mono">
                          <span className="text-green-800 font-medium">
                            {property.key}
                          </span>
                          <span className="text-gray-600">=</span>
                          <span className="text-green-700">{property.value}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {invalidProperties.length > 0 && (
                  <div>
                    <h4 className="font-medium text-red-700 mb-2">
                      Propriedades Inválidas:
                    </h4>
                    <div className="bg-red-50 p-3 rounded-md space-y-1">
                      {invalidProperties.map((property, index) => (
                        <div key={index} className="text-sm">
                          <div className="font-mono text-red-800">
                            Linha {property.lineNumber}: {property.key || '(vazio)'}
                          </div>
                          <div className="text-red-600 text-xs">
                            {property.error}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 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 || validProperties.length === 0}
        >
          {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 ConfigMapImportPropertiesPage;