import React, { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../../ui/Button';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useClassifyBatch } from '../../../../api/hooks/inventory';
import { useValidateImportFile } from '../../../../api/hooks/sales';
import type { ImportValidationResponse } from '../../../../api/types/dataImport';
import type { ProductSuggestionResponse } from '../../../../api/types/inventory';
import { Upload, FileText, AlertCircle, CheckCircle2, Loader2 } from 'lucide-react';

interface FileUploadStepProps {
  onNext: () => void;
  onPrevious: () => void;
  onComplete: (data: {
    uploadedFile: File; // NEW: Pass the file object for sales import
    validationResult: ImportValidationResponse;
    aiSuggestions: ProductSuggestionResponse[];
    uploadedFileName: string;
    uploadedFileSize: number;
  }) => void;
  isFirstStep: boolean;
  isLastStep: boolean;
}

interface ProgressState {
  stage: 'preparing' | 'validating' | 'analyzing' | 'classifying';
  progress: number;
  message: string;
}

export const FileUploadStep: React.FC<FileUploadStepProps> = ({
  onComplete,
  onPrevious,
  isFirstStep
}) => {
  const { t } = useTranslation();
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string>('');
  const [progressState, setProgressState] = useState<ProgressState | null>(null);
  const [showGuide, setShowGuide] = useState(false);
  const [validationSuccess, setValidationSuccess] = useState(false);
  const [validationDetails, setValidationDetails] = useState<{rows: number, products: number} | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const currentTenant = useCurrentTenant();

  // API hooks
  const validateFileMutation = useValidateImportFile();
  const classifyBatchMutation = useClassifyBatch();

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      setError('');
    }
  };

  const handleDrop = async (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    const file = event.dataTransfer.files[0];
    if (file) {
      setSelectedFile(file);
      setError('');
    }
  };

  const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
  };

  const handleUploadAndProcess = async () => {
    if (!selectedFile || !currentTenant?.id) return;

    setIsProcessing(true);
    setError('');
    setProgressState({
      stage: 'preparing',
      progress: 10,
      message: t('onboarding:file_upload.preparing', 'Preparando archivo...')
    });

    try {
      // Step 1: Validate the file
      setProgressState({
        stage: 'validating',
        progress: 30,
        message: t('onboarding:file_upload.validating', 'Validando formato del archivo...')
      });

      const validationResult = await validateFileMutation.mutateAsync({
        tenantId: currentTenant.id,
        file: selectedFile
      });

      if (!validationResult || validationResult.is_valid === undefined) {
        throw new Error('Invalid validation response from server');
      }

      if (!validationResult.is_valid) {
        const errorMsg = validationResult.errors?.join(', ') || 'Archivo inválido';
        throw new Error(errorMsg);
      }

      // Show validation success feedback
      setValidationSuccess(true);
      setValidationDetails({
        rows: validationResult.total_rows || 0,
        products: validationResult.product_list?.length || 0
      });

      // Step 2: Extract product list
      setProgressState({
        stage: 'analyzing',
        progress: 50,
        message: t('onboarding:file_upload.analyzing', 'Analizando productos en el archivo...')
      });

      const products = validationResult.product_list?.map((productName: string) => ({
        product_name: productName
      })) || [];

      if (products.length === 0) {
        throw new Error(t('onboarding:file_upload.no_products', 'No se encontraron productos en el archivo'));
      }

      // Step 3: AI Classification
      setProgressState({
        stage: 'classifying',
        progress: 75,
        message: t('onboarding:file_upload.classifying', `Clasificando ${products.length} productos con IA...`)
      });

      const classificationResponse = await classifyBatchMutation.mutateAsync({
        tenantId: currentTenant.id,
        products
      });

      // Step 4: Complete with success
      setProgressState({
        stage: 'classifying',
        progress: 100,
        message: t('onboarding:file_upload.success', '¡Análisis completado!')
      });

      // Pass data to parent and move to next step
      setTimeout(() => {
        onComplete({
          uploadedFile: selectedFile, // NEW: Pass the file for sales import
          validationResult,
          aiSuggestions: classificationResponse.suggestions,
          uploadedFileName: selectedFile.name,
          uploadedFileSize: selectedFile.size,
        });
      }, 500);

    } catch (err) {
      console.error('Error processing file:', err);
      setError(err instanceof Error ? err.message : 'Error procesando archivo');
      setProgressState(null);
      setIsProcessing(false);
    }
  };

  const handleRemoveFile = () => {
    setSelectedFile(null);
    setError('');
    setProgressState(null);
    setValidationSuccess(false);
    setValidationDetails(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="space-y-4 md:space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-xl md:text-2xl font-bold text-[var(--text-primary)] mb-2">
          {t('onboarding:file_upload.title', 'Subir Datos de Ventas')}
        </h2>
        <p className="text-sm md:text-base text-[var(--text-secondary)]">
          {t('onboarding:file_upload.description', 'Sube un archivo con tus datos de ventas y nuestro sistema detectará automáticamente tus productos')}
        </p>
      </div>

      {/* Why This Matters */}
      <div className="bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg p-4">
        <h3 className="font-semibold text-[var(--text-primary)] mb-2 flex items-center gap-2">
          <AlertCircle className="w-5 h-5 text-[var(--color-info)]" />
          {t('setup_wizard:why_this_matters', '¿Por qué es importante?')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('onboarding:file_upload.why', 'Analizaremos tus datos de ventas históricas para configurar automáticamente tu inventario inicial con inteligencia artificial, ahorrándote horas de trabajo manual.')}
        </p>
      </div>

      {/* File Upload Area */}
      {!selectedFile && !isProcessing && (
        <div
          onDrop={handleDrop}
          onDragOver={handleDragOver}
          className="border-2 border-dashed border-[var(--color-primary)]/30 rounded-lg p-6 md:p-8 text-center hover:border-[var(--color-primary)]/50 transition-colors cursor-pointer min-h-[200px] flex flex-col items-center justify-center"
          onClick={() => fileInputRef.current?.click()}
        >
          <Upload className="w-10 h-10 md:w-12 md:h-12 mx-auto mb-3 md:mb-4 text-[var(--color-primary)]/50" />
          <h3 className="text-base md:text-lg font-medium text-[var(--text-primary)] mb-2 px-4">
            {t('onboarding:file_upload.drop_zone_title', 'Arrastra tu archivo aquí')}
          </h3>
          <p className="text-sm text-[var(--text-secondary)] mb-3 md:mb-4">
            {t('onboarding:file_upload.drop_zone_subtitle', 'o haz clic para seleccionar')}
          </p>
          <p className="text-xs text-[var(--text-secondary)] px-4">
            {t('onboarding:file_upload.formats', 'Formatos soportados: CSV, JSON (máx. 10MB)')}
          </p>
          <input
            ref={fileInputRef}
            type="file"
            accept=".csv,.json"
            onChange={handleFileSelect}
            className="hidden"
          />
        </div>
      )}

      {/* Selected File Preview */}
      {selectedFile && !isProcessing && !validationSuccess && (
        <div className="border-2 border-[var(--color-primary)] bg-[var(--color-primary)]/5 rounded-lg p-3 md:p-4">
          <div className="flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 md:gap-3 min-w-0">
              <FileText className="w-8 h-8 md:w-10 md:h-10 text-[var(--color-primary)] flex-shrink-0" />
              <div className="min-w-0">
                <p className="font-medium text-[var(--text-primary)] text-sm md:text-base truncate">{selectedFile.name}</p>
                <p className="text-xs text-[var(--text-secondary)]">
                  {(selectedFile.size / 1024).toFixed(2)} KB
                </p>
              </div>
            </div>
            <button
              onClick={handleRemoveFile}
              className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] p-2"
            >
              ✕
            </button>
          </div>
        </div>
      )}

      {/* Validation Success State */}
      {selectedFile && validationSuccess && !isProcessing && validationDetails && (
        <div className="border-2 border-[var(--color-success)] bg-[var(--color-success)]/10 rounded-lg p-4">
          <div className="flex items-start gap-3">
            <CheckCircle2 className="w-6 h-6 text-[var(--color-success)] flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="font-semibold text-[var(--color-success)] mb-2">
                {t('onboarding:file_upload.validation_success', '¡Archivo validado correctamente!')}
              </p>
              <div className="space-y-1 text-sm">
                <div className="flex items-center justify-between">
                  <span className="text-[var(--text-secondary)]">{t('onboarding:file_upload.file_name', 'Archivo:')}</span>
                  <span className="font-medium text-[var(--text-primary)]">{selectedFile.name}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-[var(--text-secondary)]">{t('onboarding:file_upload.rows_found', 'Registros encontrados:')}</span>
                  <span className="font-medium text-[var(--text-primary)]">{validationDetails.rows}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-[var(--text-secondary)]">{t('onboarding:file_upload.products_found', 'Productos únicos:')}</span>
                  <span className="font-medium text-[var(--text-primary)]">{validationDetails.products}</span>
                </div>
              </div>
              <button
                onClick={handleRemoveFile}
                className="text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] mt-2 hover:underline"
              >
                {t('onboarding:file_upload.change_file', 'Cambiar archivo')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Progress Indicator */}
      {isProcessing && progressState && (
        <div className="border border-[var(--color-primary)] rounded-lg p-6 bg-[var(--color-primary)]/5">
          <div className="flex items-center gap-3 mb-4">
            <Loader2 className="w-6 h-6 animate-spin text-[var(--color-primary)]" />
            <div className="flex-1">
              <p className="font-medium text-[var(--text-primary)]">{progressState.message}</p>
              <div className="mt-2 bg-[var(--bg-secondary)] rounded-full h-2">
                <div
                  className="bg-[var(--color-primary)] h-2 rounded-full transition-all duration-300"
                  style={{ width: `${progressState.progress}%` }}
                />
              </div>
            </div>
          </div>
          <p className="text-sm text-[var(--text-secondary)] text-center">
            {progressState.progress}% completado
          </p>
        </div>
      )}

      {/* Error Display */}
      {error && (
        <div className="bg-[var(--color-error)]/10 border-2 border-[var(--color-error)] rounded-lg p-4">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-6 h-6 text-[var(--color-error)] flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="font-semibold text-[var(--color-error)] mb-2">
                {t('onboarding:file_upload.validation_failed', 'Error al validar el archivo')}
              </p>
              <p className="text-sm text-[var(--text-secondary)] mb-3">{error}</p>
              <div className="bg-[var(--bg-secondary)] rounded p-3 text-xs space-y-1">
                <p className="font-medium text-[var(--text-primary)] mb-1">
                  {t('onboarding:file_upload.error_tips', 'Consejos para solucionar el problema:')}
                </p>
                <ul className="list-disc list-inside space-y-0.5 text-[var(--text-secondary)]">
                  <li>{t('onboarding:file_upload.tip_1', 'Verifica que el archivo tenga las columnas: Fecha, Producto, Cantidad')}</li>
                  <li>{t('onboarding:file_upload.tip_2', 'Asegúrate de que las fechas estén en formato YYYY-MM-DD')}</li>
                  <li>{t('onboarding:file_upload.tip_3', 'Comprueba que no haya filas vacías o datos incorrectos')}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Help Guide Toggle */}
      <button
        onClick={() => setShowGuide(!showGuide)}
        className="text-sm text-[var(--color-primary)] hover:underline"
      >
        {showGuide ? '▼' : '▶'} {t('onboarding:file_upload.show_guide', '¿Necesitas ayuda con el formato del archivo?')}
      </button>

      {showGuide && (
        <div className="bg-[var(--bg-secondary)] rounded-lg p-4 text-sm space-y-2">
          <p className="font-medium text-[var(--text-primary)]">
            {t('onboarding:file_upload.guide_title', 'Formato requerido del archivo:')}
          </p>
          <ul className="list-disc list-inside space-y-1 text-[var(--text-secondary)]">
            <li>{t('onboarding:file_upload.guide_1', 'Columnas: Fecha, Producto, Cantidad')}</li>
            <li>{t('onboarding:file_upload.guide_2', 'Formato de fecha: YYYY-MM-DD')}</li>
            <li>{t('onboarding:file_upload.guide_3', 'Los nombres de productos deben ser consistentes')}</li>
            <li>{t('onboarding:file_upload.guide_4', 'Ejemplo: 2024-01-15,Pan de Molde,25')}</li>
          </ul>
        </div>
      )}

      {/* Navigation Buttons */}
      <div className="flex justify-between gap-4 pt-6 border-t">
        <Button
          variant="outline"
          onClick={onPrevious}
          disabled={isProcessing || isFirstStep}
        >
          {t('common:back', '← Atrás')}
        </Button>
        <Button
          onClick={handleUploadAndProcess}
          disabled={!selectedFile || isProcessing}
          className="min-w-[200px]"
        >
          {isProcessing ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              {t('onboarding:file_upload.processing', 'Procesando...')}
            </>
          ) : (
            t('onboarding:file_upload.continue', 'Analizar y Continuar →')
          )}
        </Button>
      </div>
    </div>
  );
};
