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

interface ParsedJsonData {
  key: string;
  value: string;
  path: string;
  isValid: boolean;
  error?: string;
}

function ConfigMapImportJsonPage() {
  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 [jsonContent, setJsonContent] = useState('');
  const [parsedData, setParsedData] = useState<ParsedJsonData[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [creating, setCreating] = useState(false);
  const [flattenMode, setFlattenMode] = useState<'dot' | 'underscore'>('dot');

  const flattenObject = (
    obj: any,
    prefix = '',
    separator = '.',
  ): Record<string, any> => {
    const flattened: Record<string, any> = {};

    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        const newKey = prefix ? `${prefix}${separator}${key}` : key;

        if (
          obj[key] !== null &&
          typeof obj[key] === 'object' &&
          !Array.isArray(obj[key])
        ) {
          Object.assign(flattened, flattenObject(obj[key], newKey, separator));
        } else {
          flattened[newKey] = obj[key];
        }
      }
    }

    return flattened;
  };

  const parseJsonFile = (content: string): ParsedJsonData[] => {
    const data: ParsedJsonData[] = [];

    try {
      const parsed = JSON.parse(content);
      const separator = flattenMode === 'dot' ? '.' : '_';
      const flattened = flattenObject(parsed, '', separator);

      for (const [key, value] of Object.entries(flattened)) {
        // Convert arrays and objects to JSON strings
        let stringValue: string;
        if (Array.isArray(value)) {
          stringValue = JSON.stringify(value);
        } else if (typeof value === 'object' && value !== null) {
          stringValue = JSON.stringify(value);
        } else {
          stringValue = String(value);
        }

        // Validate key format (should be valid ConfigMap key)
        if (!/^[a-zA-Z_][a-zA-Z0-9_.-]*$/.test(key)) {
          data.push({
            key,
            value: stringValue,
            path: key,
            isValid: false,
            error: 'Nome de chave inválido para ConfigMap',
          });
        } else {
          data.push({
            key,
            value: stringValue,
            path: key,
            isValid: true,
          });
        }
      }
    } catch (error) {
      data.push({
        key: 'json-parse-error',
        value: '',
        path: '',
        isValid: false,
        error: `Erro ao parsear JSON: ${error instanceof Error ? error.message : 'Erro desconhecido'}`,
      });
    }

    return data;
  };

  const handleContentChange = (content: string) => {
    setJsonContent(content);
    if (content.trim()) {
      const parsed = parseJsonFile(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 handleFlattenModeChange = (mode: 'dot' | 'underscore') => {
    setFlattenMode(mode);
    if (jsonContent.trim()) {
      const parsed = parseJsonFile(jsonContent);
      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} chaves`,
          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">
              <Code className="h-8 w-8 mr-3 text-blue-600" />
              Importar Arquivo JSON
            </h1>
            <p className="text-muted-foreground">
              Importe configurações de um arquivo JSON
            </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="flattenMode">Modo de Achatamento</Label>
            <Select value={flattenMode} onValueChange={handleFlattenModeChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="dot">
                  Separador por ponto (db.host)
                </SelectItem>
                <SelectItem value="underscore">
                  Separador por underscore (db_host)
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* File Upload */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Upload className="h-5 w-5 mr-2" />
            Arquivo JSON
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="jsonFile">Carregar arquivo JSON</Label>
            <input
              type="file"
              accept=".json"
              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="jsonContent">Ou cole o conteúdo JSON</Label>
            <Textarea
              id="jsonContent"
              placeholder={`{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp"
  },
  "api": {
    "url": "https://api.example.com",
    "timeout": 30
  },
  "features": ["auth", "logging"]
}`}
              value={jsonContent}
              onChange={(e) => handleContentChange(e.target.value)}
              rows={10}
              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} chaves 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} chaves inválidas
                  </span>
                </div>
              )}
            </div>

            {showPreview && (
              <div className="space-y-4">
                {validData.length > 0 && (
                  <div>
                    <h4 className="font-medium text-green-700 mb-2">
                      Chaves 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>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {invalidData.length > 0 && (
                  <div>
                    <h4 className="font-medium text-red-700 mb-2">
                      Chaves 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">
                            {item.key || '(erro)'}
                          </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 ConfigMapImportJsonPage;
