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

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

function ConfigMapImportIniPage() {
  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 [iniContent, setIniContent] = useState('');
  const [parsedData, setParsedData] = useState<ParsedIniData[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);
  const [includeSection, setIncludeSection] = useState<'yes' | 'no'>('yes');

  const parseIniFile = (content: string): ParsedIniData[] => {
    const lines = content.split('\n');
    const data: ParsedIniData[] = [];
    let currentSection = '';

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

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

      // Check if it's a section header
      if (trimmedLine.startsWith('[') && trimmedLine.endsWith(']')) {
        currentSection = trimmedLine.slice(1, -1);
        return;
      }

      // Parse key-value pair
      const equalIndex = trimmedLine.indexOf('=');
      if (equalIndex === -1) {
        data.push({
          key: trimmedLine,
          value: '',
          section: currentSection,
          lineNumber: index + 1,
          isValid: false,
          error: 'Formato inválido: faltando símbolo "="',
        });
        return;
      }

      const key = trimmedLine.substring(0, equalIndex).trim();
      const value = trimmedLine.substring(equalIndex + 1).trim();

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

      // Create the final key name
      let finalKey = key;
      if (includeSection === 'yes' && currentSection) {
        finalKey = `${currentSection}.${key}`;
      }

      // Remove quotes from value if present
      let processedValue = value;
      if ((value.startsWith('"') && value.endsWith('"')) || 
          (value.startsWith("'") && value.endsWith("'"))) {
        processedValue = value.slice(1, -1);
      }

      // Validate key format (should be valid ConfigMap key)
      if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(finalKey)) {
        data.push({
          key: finalKey,
          value: processedValue,
          section: currentSection,
          lineNumber: index + 1,
          isValid: false,
          error: 'Nome de chave inválido para ConfigMap',
        });
        return;
      }

      data.push({
        key: finalKey,
        value: processedValue,
        section: currentSection,
        lineNumber: index + 1,
        isValid: true,
      });
    });

    return data;
  };

  const handleContentChange = (content: string) => {
    setIniContent(content);
    if (content.trim()) {
      const parsed = parseIniFile(content);
      setParsedData(parsed);
    } else {
      setParsedData([]);
    }
  };

  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 handleIncludeSectionChange = (value: 'yes' | 'no') => {
    setIncludeSection(value);
    if (iniContent.trim()) {
      const parsed = parseIniFile(iniContent);
      setParsedData(parsed);
    }
  };

  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 validData = parsedData.filter((d) => d.isValid);
    if (validData.length === 0) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nenhum dado válido encontrado',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const validData = parsedData.filter((d) => d.isValid);

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

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

      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'ConfigMap Criado com Sucesso',
          description: `ConfigMap "${configMapName}" foi criado com ${validData.length} entradas`,
          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 validData = parsedData.filter((d) => d.isValid);
  const invalidData = parsedData.filter((d) => !d.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">
              <FileText className="h-8 w-8 mr-3 text-indigo-600" />
              Importar Arquivo .ini
            </h1>
            <p className="text-muted-foreground">
              Importe configurações de um arquivo INI
            </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>

          <div>
            <Label htmlFor="includeSection">Incluir Seção no Nome da Chave</Label>
            <Select value={includeSection} onValueChange={handleIncludeSectionChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="yes">
                  Sim - database.host (section.key)
                </SelectItem>
                <SelectItem value="no">
                  Não - host (apenas key)
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* File Upload */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Upload className="h-5 w-5 mr-2" />
            Arquivo .ini
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="iniFile">Carregar arquivo .ini</Label>
            <input
              type="file"
              accept=".ini,.cfg,.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="iniContent">Ou cole o conteúdo do arquivo .ini</Label>
            <Textarea
              id="iniContent"
              placeholder={`# Exemplo de arquivo .ini
[database]
host=localhost
port=5432
name=myapp
ssl=true

[api]
url=https://api.example.com
timeout=30000
retries=3

[logging]
level=INFO
format=JSON
file=/var/log/app.log

[cache]
enabled=true
size=1000
ttl=3600`}
              value={iniContent}
              onChange={(e) => handleContentChange(e.target.value)}
              rows={12}
              className="font-mono text-sm"
            />
          </div>
        </CardContent>
      </Card>

      {/* Preview */}
      {parsedData.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">
                  {validData.length} entradas válidas
                </span>
              </div>
              {invalidData.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">
                    {invalidData.length} entradas inválidas
                  </span>
                </div>
              )}
            </div>

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

                {invalidData.length > 0 && (
                  <div>
                    <h4 className="font-medium text-red-700 mb-2">
                      Entradas Inválidas:
                    </h4>
                    <div className="bg-red-50 p-3 rounded-md space-y-1">
                      {invalidData.map((item, index) => (
                        <div key={index} className="text-sm">
                          <div className="font-mono text-red-800">
                            Linha {item.lineNumber}: {item.key || '(vazio)'}
                            {item.section && (
                              <span className="text-gray-500 ml-2 text-xs">
                                [{item.section}]
                              </span>
                            )}
                          </div>
                          <div className="text-red-600 text-xs">
                            {item.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 || validData.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 ConfigMapImportIniPage;