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 ParsedEnvVar {
  key: string;
  value: string;
  lineNumber: number;
  isValid: boolean;
  error?: string;
}

function ConfigMapImportEnvPage() {
  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 [envContent, setEnvContent] = useState('');
  const [parsedVars, setParsedVars] = useState<ParsedEnvVar[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);

  const parseEnvFile = (content: string): ParsedEnvVar[] => {
    const lines = content.split('\n');
    const vars: ParsedEnvVar[] = [];

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

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

      const equalsIndex = trimmedLine.indexOf('=');
      if (equalsIndex === -1) {
        vars.push({
          key: trimmedLine,
          value: '',
          lineNumber: index + 1,
          isValid: false,
          error: 'Formato inválido: faltando símbolo "="',
        });
        return;
      }

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

      // Remove quotes if present
      const cleanValue = value.replace(/^["']|["']$/g, '');

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

      // Validate key format (should be valid env var name)
      if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
        vars.push({
          key,
          value: cleanValue,
          lineNumber: index + 1,
          isValid: false,
          error: 'Nome de variável inválido',
        });
        return;
      }

      vars.push({
        key,
        value: cleanValue,
        lineNumber: index + 1,
        isValid: true,
      });
    });

    return vars;
  };

  const handleContentChange = (content: string) => {
    setEnvContent(content);
    if (content.trim()) {
      const parsed = parseEnvFile(content);
      setParsedVars(parsed);
    } else {
      setParsedVars([]);
    }
  };

  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 validVars = parsedVars.filter((v) => v.isValid);
    if (validVars.length === 0) {
      showToast({
        title: 'Erro de Validação',
        description: 'Nenhuma variável válida encontrada',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

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

    setCreating(true);
    try {
      const validVars = parsedVars.filter((v) => v.isValid);

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

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

      const result = await executeCommand(command);

      if (result.success) {
        showToast({
          title: 'ConfigMap Criado com Sucesso',
          description: `ConfigMap "${configMapName}" foi criado com ${validVars.length} variáveis`,
          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 validVars = parsedVars.filter((v) => v.isValid);
  const invalidVars = parsedVars.filter((v) => !v.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-green-600" />
              Importar Arquivo .env
            </h1>
            <p className="text-muted-foreground">
              Importe variáveis de ambiente de um arquivo .env
            </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 .env
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="envFile">Carregar arquivo .env</Label>
            <input
              type="file"
              accept=".env,.txt"
              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="envContent">
              Ou cole o conteúdo do arquivo .env
            </Label>
            <Textarea
              id="envContent"
              placeholder={`# Exemplo de arquivo .env
DATABASE_URL=postgresql://user:pass@localhost/db
API_KEY=your-api-key-here
DEBUG=true
PORT=3000`}
              value={envContent}
              onChange={(e) => handleContentChange(e.target.value)}
              rows={8}
              className="font-mono text-sm"
            />
          </div>
        </CardContent>
      </Card>

      {/* Preview */}
      {parsedVars.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">
                  {validVars.length} variáveis válidas
                </span>
              </div>
              {invalidVars.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">
                    {invalidVars.length} variáveis inválidas
                  </span>
                </div>
              )}
            </div>

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

                {invalidVars.length > 0 && (
                  <div>
                    <h4 className="font-medium text-red-700 mb-2">
                      Variáveis Inválidas:
                    </h4>
                    <div className="bg-red-50 p-3 rounded-md space-y-1">
                      {invalidVars.map((envVar, index) => (
                        <div key={index} className="text-sm">
                          <div className="font-mono text-red-800">
                            Linha {envVar.lineNumber}: {envVar.key || '(vazio)'}
                          </div>
                          <div className="text-red-600 text-xs">
                            {envVar.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 || validVars.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 ConfigMapImportEnvPage;
