import React, { useState, useRef, useEffect } 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 { Checkbox } from '@/components/ui/checkbox';
import { useKubectl, useNamespacesInfo } from '@/hooks/useKubectl';
import { useToast } from '@/hooks/useToast';
import { useGlobalNamespace } from '@/hooks/useGlobalNamespace';
import { Badge } from '@/components/ui/badge';
import {
  ArrowLeft,
  Cloud,
  FileText,
  Upload,
  CheckCircle,
  AlertTriangle,
  Loader2,
  FolderOpen,
} from 'lucide-react';

interface ECSTaskDefinition {
  family: string;
  containerDefinitions: Array<{
    name: string;
    image: string;
    cpu?: number;
    memory?: number;
    memoryReservation?: number;
    essential?: boolean;
    portMappings?: Array<{
      name?: string;
      containerPort: number;
      hostPort?: number;
      protocol?: string;
    }>;
    environment?: Array<{
      name: string;
      value: string;
    }>;
    secrets?: Array<{
      name: string;
      valueFrom: string;
    }>;
    mountPoints?: Array<{
      sourceVolume: string;
      containerPath: string;
      readOnly?: boolean;
    }>;
    logConfiguration?: {
      logDriver: string;
      options?: Record<string, string>;
    };
  }>;
  volumes?: Array<{
    name: string;
    host?: {
      sourcePath?: string;
    };
  }>;
  networkMode?: string;
  requiresCompatibilities?: string[];
  cpu?: string;
  memory?: string;
  executionRoleArn?: string;
  taskRoleArn?: string;
}

export function StatefulSetImportECSPage() {
  const navigate = useNavigate();
  const { executeCommand } = useKubectl();
  const { showToast } = useToast();
  const { selectedNamespace, setSelectedNamespace } = useGlobalNamespace();
  const { namespaces: namespacesData, loading: namespacesLoading } =
    useNamespacesInfo();

  const [jsonInput, setJsonInput] = useState('');
  const [statefulSetName, setStatefulSetName] = useState('');
  const [replicas, setReplicas] = useState(() => {
    // Recupera o valor salvo ou usa '1' como padrão
    return localStorage.getItem('ecs-import-replicas') || '1';
  });
  const [parsedConfig, setParsedConfig] = useState<ECSTaskDefinition | null>(
    null,
  );
  const [parseError, setParseError] = useState('');
  const [converting, setConverting] = useState(false);
  const [createService, setCreateService] = useState(() => {
    const saved = localStorage.getItem('ecs-import-create-service');
    return saved ? saved === 'true' : true;
  });
  const [createConfigMap, setCreateConfigMap] = useState(() => {
    const saved = localStorage.getItem('ecs-import-create-configmap');
    return saved ? saved === 'true' : true;
  });
  const [createSecrets, setCreateSecrets] = useState(() => {
    const saved = localStorage.getItem('ecs-import-create-secrets');
    return saved ? saved === 'true' : true;
  });
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  // Get namespace names from the namespace objects
  const namespaces = namespacesData.map((ns) => ns.name).sort();

  // Salva as preferências quando mudarem
  useEffect(() => {
    localStorage.setItem('ecs-import-replicas', replicas);
  }, [replicas]);

  useEffect(() => {
    localStorage.setItem('ecs-import-create-service', createService.toString());
  }, [createService]);

  useEffect(() => {
    localStorage.setItem(
      'ecs-import-create-configmap',
      createConfigMap.toString(),
    );
  }, [createConfigMap]);

  useEffect(() => {
    localStorage.setItem('ecs-import-create-secrets', createSecrets.toString());
  }, [createSecrets]);

  // Function to sanitize names for Kubernetes resources
  const sanitizeKubernetesName = (name: string): string => {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9-]/g, '-') // Replace invalid chars with hyphens
      .replace(/^-+|-+$/g, '') // Remove leading/trailing hyphens
      .replace(/-+/g, '-'); // Replace multiple hyphens with single
  };

  const handleFileSelect = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (!file.name.toLowerCase().endsWith('.json')) {
        showToast({
          title: 'Arquivo Inválido',
          description: 'Por favor, selecione um arquivo .json',
          variant: 'destructive',
        });
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target?.result as string;
        setJsonInput(content);

        // Auto-parse the JSON
        try {
          const parsed = JSON.parse(content);
          setParsedConfig(parsed);
          setParseError('');

          // Auto-fill statefulset name from family
          if (parsed.family && !statefulSetName) {
            setStatefulSetName(sanitizeKubernetesName(parsed.family));
          }

          showToast({
            title: 'Arquivo Carregado',
            description: `Task Definition "${parsed.family}" carregada com sucesso`,
            variant: 'success',
          });
        } catch (error) {
          setParseError('JSON inválido no arquivo selecionado.');
          setParsedConfig(null);
          showToast({
            title: 'Erro no Arquivo',
            description: 'O arquivo selecionado não contém JSON válido',
            variant: 'destructive',
          });
        }
      };
      reader.readAsText(file);
    }

    // Reset the input to allow selecting the same file again
    event.target.value = '';
  };

  const handleParseJSON = () => {
    try {
      const parsed = JSON.parse(jsonInput);
      setParsedConfig(parsed);
      setParseError('');

      // Auto-fill statefulset name from family
      if (parsed.family && !statefulSetName) {
        setStatefulSetName(sanitizeKubernetesName(parsed.family));
      }
    } catch (error) {
      setParseError('JSON inválido. Verifique a sintaxe.');
      setParsedConfig(null);
    }
  };

  const createConfigMapYaml = (ecsConfig: ECSTaskDefinition): string | null => {
    const container = ecsConfig.containerDefinitions[0];
    const envVars = container.environment || [];

    if (envVars.length === 0) return null;

    const dataEntries = envVars
      .map((env) => `  ${env.name}: "${env.value}"`)
      .join('\n');

    return `apiVersion: v1
kind: ConfigMap
metadata:
  name: ${statefulSetName}-config
  namespace: ${selectedNamespace === 'all' ? 'default' : selectedNamespace}
  labels:
    app: ${statefulSetName}
    imported-from: aws-ecs
data:
${dataEntries}`;
  };

  const createSecretYaml = (ecsConfig: ECSTaskDefinition): string | null => {
    const container = ecsConfig.containerDefinitions[0];
    const secrets = container.secrets || [];

    if (secrets.length === 0) return null;

    const dataEntries = secrets
      .map((secret) => `  ${secret.name}: Y2hhbmdlbWU=`)
      .join('\n');

    return `apiVersion: v1
kind: Secret
metadata:
  name: ${statefulSetName}-secrets
  namespace: ${selectedNamespace === 'all' ? 'default' : selectedNamespace}
  labels:
    app: ${statefulSetName}
    imported-from: aws-ecs
type: Opaque
data:
${dataEntries}`;
  };

  const createServiceYaml = (ecsConfig: ECSTaskDefinition): string | null => {
    const container = ecsConfig.containerDefinitions[0];
    const ports = container.portMappings || [];

    if (ports.length === 0) return null;

    const portEntries = ports
      .map((port) => {
        const portName = port.name
          ? sanitizeKubernetesName(port.name)
          : `port-${port.containerPort}`;

        return `    - name: "${portName}"
      port: ${port.containerPort}
      targetPort: ${port.containerPort}
      protocol: ${port.protocol?.toUpperCase() || 'TCP'}`;
      })
      .join('\n');

    return `apiVersion: v1
kind: Service
metadata:
  name: ${statefulSetName}-service
  namespace: ${selectedNamespace === 'all' ? 'default' : selectedNamespace}
  labels:
    app: ${statefulSetName}
    imported-from: aws-ecs
spec:
  selector:
    app: ${statefulSetName}
  ports:
${portEntries}
  type: ClusterIP`;
  };

  const convertECSToKubernetes = (ecsConfig: ECSTaskDefinition): string => {
    const container = ecsConfig.containerDefinitions[0]; // Assume primeiro container

    // Add secrets if creating them
    const secretEnvVars: Array<string> = [];
    const secrets = container.secrets || [];
    if (createSecrets && secrets.length > 0) {
      secrets.forEach((secret) => {
        secretEnvVars.push(`          - name: ${secret.name}
            valueFrom:
              secretKeyRef:
                name: ${statefulSetName}-secrets
                key: ${secret.name}`);
      });
    }

    // Direct environment variables if not using ConfigMap
    const directEnvVars: Array<string> = [];
    if (!createConfigMap && container.environment) {
      container.environment.forEach((env) => {
        directEnvVars.push(`          - name: ${env.name}
            value: "${env.value}"`);
      });
    }

    const allEnvVars = [...directEnvVars, ...secretEnvVars];
    const envSection =
      allEnvVars.length > 0
        ? `
          env:
${allEnvVars.join('\n')}`
        : '';

    const envFromSection =
      createConfigMap &&
      container.environment &&
      container.environment.length > 0
        ? `
          envFrom:
            - configMapRef:
                name: ${statefulSetName}-config`
        : '';

    const portsSection =
      container.portMappings && container.portMappings.length > 0
        ? `
          ports:
${container.portMappings
  .map(
    (port) => `            - containerPort: ${port.containerPort}
              protocol: ${port.protocol?.toUpperCase() || 'TCP'}`,
  )
  .join('\n')}`
        : '';

    const resourcesSection =
      ecsConfig.cpu || ecsConfig.memory
        ? `
          resources:
            requests:${
              ecsConfig.cpu
                ? `
              cpu: "${parseInt(ecsConfig.cpu)}m"`
                : ''
            }${
              ecsConfig.memory
                ? `
              memory: "${ecsConfig.memory}Mi"`
                : ''
            }
            limits:${
              ecsConfig.cpu
                ? `
              cpu: "${parseInt(ecsConfig.cpu)}m"`
                : ''
            }${
              ecsConfig.memory
                ? `
              memory: "${ecsConfig.memory}Mi"`
                : ''
            }`
        : '';

    // Volume mounts
    const volumeMounts = container.mountPoints || [];
    const volumeMountsSection =
      volumeMounts.length > 0
        ? `
          volumeMounts:
${volumeMounts
  .map(
    (mount) => `            - name: ${mount.sourceVolume}
              mountPath: ${mount.containerPath}
              readOnly: ${mount.readOnly || false}`,
  )
  .join('\n')}`
        : '';

    // Volumes section for StatefulSet
    const volumes = ecsConfig.volumes || [];
    const volumesSection =
      volumes.length > 0
        ? `
      volumes:
${volumes
  .map(
    (volume) => `        - name: ${volume.name}
          hostPath:
            path: ${volume.host?.sourcePath || '/tmp'}`,
  )
  .join('\n')}`
        : '';

    return `apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: ${statefulSetName}
  namespace: ${selectedNamespace === 'all' ? 'default' : selectedNamespace}
  labels:
    app: ${statefulSetName}
    imported-from: aws-ecs
spec:
  replicas: ${parseInt(replicas)}
  serviceName: ${statefulSetName}-service
  selector:
    matchLabels:
      app: ${statefulSetName}
  template:
    metadata:
      labels:
        app: ${statefulSetName}
    spec:
      containers:
        - name: ${sanitizeKubernetesName(container.name)}
          image: ${container.image}${portsSection}${envSection}${envFromSection}${resourcesSection}${volumeMountsSection}${volumesSection}`;
  };

  const handleCreateStatefulSet = async () => {
    if (!parsedConfig || !statefulSetName) return;

    setConverting(true);
    try {
      const resources: string[] = [];

      // Create ConfigMap if needed
      if (createConfigMap) {
        const configMapYaml = createConfigMapYaml(parsedConfig);
        if (configMapYaml) {
          resources.push(configMapYaml);
        }
      }

      // Create Secret if needed
      if (createSecrets) {
        const secretYaml = createSecretYaml(parsedConfig);
        if (secretYaml) {
          resources.push(secretYaml);
        }
      }

      // Create StatefulSet
      const kubernetesConfig = convertECSToKubernetes(parsedConfig);
      resources.push(kubernetesConfig);

      // Create Service if needed
      if (createService) {
        const serviceYaml = createServiceYaml(parsedConfig);
        if (serviceYaml) {
          resources.push(serviceYaml);
        }
      }

      // Apply all resources
      const allResources = resources.join('\n---\n');
      const tempFile = `/tmp/ecs-import-${Date.now()}.yaml`;
      const writeCommand = `echo '${allResources.replace(/'/g, "'\"'\"'")}' > ${tempFile}`;

      await executeCommand(writeCommand);
      const applyResult = await executeCommand(`kubectl apply -f ${tempFile}`);

      // Cleanup
      executeCommand(`rm -f ${tempFile}`);

      if (applyResult.success) {
        const resourcesCreated = [];
        if (createConfigMap && createConfigMapYaml(parsedConfig))
          resourcesCreated.push('ConfigMap');
        if (createSecrets && createSecretYaml(parsedConfig))
          resourcesCreated.push('Secret');
        resourcesCreated.push('StatefulSet');
        if (createService && createServiceYaml(parsedConfig))
          resourcesCreated.push('Service');

        showToast({
          title: 'Recursos Criados',
          description: `${resourcesCreated.join(', ')} criados com sucesso: "${statefulSetName}"`,
          variant: 'success',
        });

        // Navigate immediately to statefulsets list
        navigate('/workloads/statefulsets');
      } else {
        showToast({
          title: 'Erro ao Criar Recursos',
          description: applyResult.error || 'Falha ao aplicar configuração',
          variant: 'destructive',
        });
      }
    } catch (error) {
      showToast({
        title: 'Erro',
        description: error instanceof Error ? error.message : 'Erro inesperado',
        variant: 'destructive',
      });
    } finally {
      setConverting(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">
              <Cloud className="h-8 w-8 mr-3 text-blue-600" />
              Importar AWS ECS Task Definition
            </h1>
            <p className="text-muted-foreground">
              Cole o JSON da Task Definition do ECS para converter em
              StatefulSet Kubernetes
            </p>
          </div>
        </div>
      </div>

      {/* Wizard Steps */}
      <div className="flex items-center space-x-4 text-sm">
        <div className="flex items-center">
          <div className="w-8 h-8 bg-gray-200 text-gray-600 rounded-full flex items-center justify-center font-medium">
            1
          </div>
          <span className="ml-2 text-gray-600">Tipo de Importação</span>
        </div>
        <div className="h-px bg-gray-300 flex-1" />
        <div className="flex items-center">
          <div className="w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center font-medium">
            2
          </div>
          <span className="ml-2 font-medium">Configuração ECS</span>
        </div>
        <div className="h-px bg-gray-300 flex-1" />
        <div className="flex items-center">
          <div className="w-8 h-8 bg-gray-200 text-gray-600 rounded-full flex items-center justify-center font-medium">
            3
          </div>
          <span className="ml-2 text-gray-600">Revisão</span>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Input Section */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <FileText className="h-5 w-5 mr-2" />
              Task Definition JSON
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="json-input">Cole o JSON da Task Definition</Label>
              <Textarea
                id="json-input"
                placeholder='{"family": "my-app", "containerDefinitions": [...], ...}'
                value={jsonInput}
                onChange={(e) => setJsonInput(e.target.value)}
                rows={12}
                className="font-mono text-sm"
              />
            </div>

            {/* Hidden file input */}
            <input
              ref={fileInputRef}
              type="file"
              accept=".json"
              onChange={handleFileChange}
              style={{ display: 'none' }}
            />

            <div className="flex gap-2">
              <Button onClick={handleFileSelect} variant="outline">
                <FolderOpen className="h-4 w-4 mr-2" />
                Localizar
              </Button>
              <Button onClick={handleParseJSON} disabled={!jsonInput.trim()}>
                <FileText className="h-4 w-4 mr-2" />
                Analisar JSON
              </Button>
            </div>

            {parseError && (
              <div className="flex items-center text-red-600 text-sm">
                <AlertTriangle className="h-4 w-4 mr-2" />
                {parseError}
              </div>
            )}

            {parsedConfig && (
              <div className="flex items-center text-green-600 text-sm">
                <CheckCircle className="h-4 w-4 mr-2" />
                JSON válido! Family: {parsedConfig.family}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Configuration Section */}
        <Card>
          <CardHeader>
            <CardTitle>Configuração do StatefulSet</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="statefulset-name">Nome do StatefulSet</Label>
              <Input
                id="statefulset-name"
                placeholder="my-app"
                value={statefulSetName}
                onChange={(e) => setStatefulSetName(e.target.value)}
              />
            </div>

            <div>
              <Label htmlFor="namespace">Namespace</Label>
              <Select
                value={
                  selectedNamespace === 'all' ? 'default' : selectedNamespace
                }
                onValueChange={setSelectedNamespace}
                disabled={namespacesLoading}
              >
                <SelectTrigger>
                  <SelectValue
                    placeholder={
                      namespacesLoading
                        ? 'Carregando namespaces...'
                        : 'Selecione o namespace'
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  {namespaces.map((ns) => (
                    <SelectItem key={ns} value={ns}>
                      {ns}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="replicas">Número de Réplicas</Label>
              <Input
                id="replicas"
                type="number"
                min="1"
                max="100"
                value={replicas}
                onChange={(e) => setReplicas(e.target.value)}
              />
            </div>

            {parsedConfig && (
              <>
                <div className="space-y-3">
                  <h4 className="font-medium">Recursos a Criar:</h4>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="create-service"
                      checked={createService}
                      onChange={(e) => setCreateService(e.target.checked)}
                      disabled={
                        !parsedConfig.containerDefinitions[0]?.portMappings
                          ?.length
                      }
                    />
                    <Label htmlFor="create-service" className="text-sm">
                      Service{' '}
                      {!parsedConfig.containerDefinitions[0]?.portMappings
                        ?.length && '(sem portas disponíveis)'}
                    </Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="create-configmap"
                      checked={createConfigMap}
                      onChange={(e) => setCreateConfigMap(e.target.checked)}
                      disabled={
                        !parsedConfig.containerDefinitions[0]?.environment
                          ?.length
                      }
                    />
                    <Label htmlFor="create-configmap" className="text-sm">
                      ConfigMap{' '}
                      {!parsedConfig.containerDefinitions[0]?.environment
                        ?.length && '(sem variáveis de ambiente)'}
                    </Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="create-secrets"
                      checked={createSecrets}
                      onChange={(e) => setCreateSecrets(e.target.checked)}
                      disabled={
                        !parsedConfig.containerDefinitions[0]?.secrets?.length
                      }
                    />
                    <Label htmlFor="create-secrets" className="text-sm">
                      Secrets{' '}
                      {!parsedConfig.containerDefinitions[0]?.secrets?.length &&
                        '(sem secrets disponíveis)'}
                    </Label>
                  </div>
                </div>

                <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-medium mb-2">Preview da Configuração:</h4>
                  <div className="text-sm space-y-1">
                    <p>
                      <strong>Container:</strong>{' '}
                      {parsedConfig.containerDefinitions[0]?.name}
                    </p>
                    <p>
                      <strong>Imagem:</strong>{' '}
                      {parsedConfig.containerDefinitions[0]?.image}
                    </p>
                    <p>
                      <strong>CPU:</strong>{' '}
                      {parsedConfig.cpu || 'Não especificado'}
                    </p>
                    <p>
                      <strong>Memória:</strong>{' '}
                      {parsedConfig.memory || 'Não especificado'}
                    </p>
                    <p>
                      <strong>Portas:</strong>{' '}
                      {parsedConfig.containerDefinitions[0]?.portMappings
                        ?.map((p) => p.containerPort)
                        .join(', ') || 'Nenhuma'}
                    </p>
                    <p>
                      <strong>Environment Vars:</strong>{' '}
                      {parsedConfig.containerDefinitions[0]?.environment
                        ?.length || 0}
                    </p>
                    <p>
                      <strong>Secrets:</strong>{' '}
                      {parsedConfig.containerDefinitions[0]?.secrets?.length ||
                        0}
                    </p>
                    <p className="text-xs text-muted-foreground mt-2">
                      <strong>Nota:</strong> StatefulSets suportam
                      volumeClaimTemplates para armazenamento persistente. Para
                      volumes avançados, edite o manifest após a criação.
                    </p>
                  </div>

                  {(createService || createConfigMap || createSecrets) && (
                    <div className="mt-3 pt-3 border-t border-gray-200">
                      <p className="text-sm font-medium mb-1">
                        Recursos que serão criados:
                      </p>
                      <div className="flex flex-wrap gap-1">
                        <Badge variant="outline">StatefulSet</Badge>
                        {createService && createServiceYaml(parsedConfig) && (
                          <Badge variant="outline">Service</Badge>
                        )}
                        {createConfigMap &&
                          createConfigMapYaml(parsedConfig) && (
                            <Badge variant="outline">ConfigMap</Badge>
                          )}
                        {createSecrets && createSecretYaml(parsedConfig) && (
                          <Badge variant="outline">Secret</Badge>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Navigation */}
      <div className="flex justify-end">
        <Button
          onClick={handleCreateStatefulSet}
          disabled={!parsedConfig || !statefulSetName || converting}
        >
          {converting ? (
            <>
              <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              Criando StatefulSet...
            </>
          ) : (
            <>
              <Upload className="h-4 w-4 mr-2" />
              Criar StatefulSet
            </>
          )}
        </Button>
      </div>
    </div>
  );
}
