import React, { useState, useCallback } from 'react';
import { Upload, X, CheckCircle2, AlertCircle, FileText, Download, Users } from 'lucide-react';
import type { SupplierCreate, SupplierType, SupplierStatus, PaymentTerms } from '../../../api/types/suppliers';

interface BulkSupplierImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  onImport: (suppliers: SupplierCreate[]) => Promise<void>;
}

interface ParsedSupplier {
  data: Partial<SupplierCreate>;
  row: number;
  isValid: boolean;
  errors: string[];
}

export const BulkSupplierImportModal: React.FC<BulkSupplierImportModalProps> = ({
  isOpen,
  onClose,
  onImport
}) => {
  const [file, setFile] = useState<File | null>(null);
  const [parsedSuppliers, setParsedSuppliers] = useState<ParsedSupplier[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [importStatus, setImportStatus] = useState<'idle' | 'success' | 'error'>('idle');

  const handleFileSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile && selectedFile.type === 'text/csv') {
      setFile(selectedFile);
      parseCSV(selectedFile);
    } else {
      alert('Por favor selecciona un archivo CSV válido');
    }
  }, []);

  const parseCSV = async (file: File) => {
    setIsProcessing(true);
    try {
      const text = await file.text();
      const lines = text.split('\n').filter(line => line.trim());

      // Parse header
      const headers = lines[0].split(',').map(h => h.trim().toLowerCase());

      // Parse data rows
      const parsed: ParsedSupplier[] = [];
      for (let i = 1; i < lines.length; i++) {
        const values = lines[i].split(',').map(v => v.trim());
        const supplier: Partial<SupplierCreate> = {};
        const errors: string[] = [];

        // Map CSV columns to supplier fields
        headers.forEach((header, index) => {
          const value = values[index];

          switch (header) {
            case 'name':
            case 'nombre':
              supplier.name = value;
              if (!value) errors.push('Nombre requerido');
              break;
            case 'type':
            case 'tipo':
              supplier.supplier_type = value as SupplierType;
              if (!value) errors.push('Tipo requerido');
              break;
            case 'email':
            case 'correo':
              supplier.email = value || null;
              break;
            case 'phone':
            case 'telefono':
            case 'teléfono':
              supplier.phone = value || null;
              break;
            case 'contact':
            case 'contacto':
              supplier.contact_person = value || null;
              break;
            case 'payment_terms':
            case 'pago':
              supplier.payment_terms = (value || 'net_30') as PaymentTerms;
              break;
            case 'status':
            case 'estado':
              supplier.status = (value || 'pending_approval') as SupplierStatus;
              break;
            case 'tax_id':
            case 'cif':
            case 'nif':
              supplier.tax_id = value || null;
              break;
            case 'address':
            case 'direccion':
            case 'dirección':
              supplier.address_street = value || null;
              break;
            case 'city':
            case 'ciudad':
              supplier.address_city = value || null;
              break;
            case 'postal_code':
            case 'codigo_postal':
            case 'código_postal':
              supplier.address_postal_code = value || null;
              break;
            case 'country':
            case 'pais':
            case 'país':
              supplier.address_country = value || null;
              break;
            case 'lead_time':
            case 'tiempo_entrega':
              supplier.lead_time_days = value ? parseInt(value) : null;
              break;
            case 'minimum_order':
            case 'pedido_minimo':
              supplier.minimum_order_value = value ? parseFloat(value) : null;
              break;
            case 'notes':
            case 'notas':
              supplier.notes = value || null;
              break;
          }
        });

        // Add default values
        if (!supplier.status) supplier.status = 'pending_approval' as SupplierStatus;
        if (!supplier.payment_terms) supplier.payment_terms = 'net_30' as PaymentTerms;
        if (!supplier.currency) supplier.currency = 'EUR';
        if (!supplier.quality_rating) supplier.quality_rating = 0;
        if (!supplier.delivery_rating) supplier.delivery_rating = 0;
        if (!supplier.pricing_rating) supplier.pricing_rating = 0;
        if (!supplier.overall_rating) supplier.overall_rating = 0;

        parsed.push({
          data: supplier,
          row: i + 1,
          isValid: errors.length === 0 && !!supplier.name && !!supplier.supplier_type,
          errors
        });
      }

      setParsedSuppliers(parsed);
    } catch (error) {
      console.error('Error parsing CSV:', error);
      alert('Error al procesar el archivo CSV');
    } finally {
      setIsProcessing(false);
    }
  };

  const handleImport = async () => {
    const validSuppliers = parsedSuppliers.filter(p => p.isValid);
    if (validSuppliers.length === 0) {
      alert('No hay proveedores válidos para importar');
      return;
    }

    setIsProcessing(true);
    try {
      const suppliersToImport: SupplierCreate[] = validSuppliers.map(p => {
        const supplier = p.data as SupplierCreate;
        // Generate supplier code
        supplier.supplier_code = supplier.supplier_code ||
          (supplier.name?.substring(0, 3).toUpperCase() || 'SUP') +
          String(Date.now() + p.row).slice(-3);
        return supplier;
      });

      await onImport(suppliersToImport);
      setImportStatus('success');

      // Reset after 2 seconds
      setTimeout(() => {
        handleClose();
      }, 2000);
    } catch (error) {
      console.error('Error importing suppliers:', error);
      setImportStatus('error');
    } finally {
      setIsProcessing(false);
    }
  };

  const handleClose = () => {
    setFile(null);
    setParsedSuppliers([]);
    setImportStatus('idle');
    onClose();
  };

  const downloadTemplate = () => {
    const template = `name,type,email,phone,contact,payment_terms,status,tax_id,address,city,postal_code,country,lead_time,minimum_order,notes
Molinos La Victoria,ingredients,info@molinos.com,+34 600 000 000,Juan Pérez,net_30,active,B12345678,Calle Mayor 123,Madrid,28001,España,3,100,Proveedor principal de harina
Empaques del Sur,packaging,ventas@empaques.com,+34 600 000 001,María García,net_15,active,B98765432,Av. Industrial 45,Barcelona,08001,España,5,50,Empaques biodegradables`;

    const blob = new Blob([template], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'plantilla_proveedores.csv';
    a.click();
    window.URL.revokeObjectURL(url);
  };

  const validCount = parsedSuppliers.filter(p => p.isValid).length;
  const invalidCount = parsedSuppliers.length - validCount;

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={handleClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-4xl max-h-[90vh] bg-[var(--bg-primary)] rounded-xl shadow-2xl flex flex-col overflow-hidden">
        {/* Header */}
        <div className="px-6 py-5 border-b border-[var(--border-secondary)] bg-gradient-to-r from-[var(--color-primary)]/5 to-[var(--color-primary)]/10">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-[var(--color-primary)] flex items-center justify-center">
                <Upload className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-xl font-semibold text-[var(--text-primary)]">
                  Importar Proveedores (CSV)
                </h2>
                <p className="text-sm text-[var(--text-secondary)]">
                  Carga múltiples proveedores desde un archivo CSV
                </p>
              </div>
            </div>
            <button
              onClick={handleClose}
              className="p-2 hover:bg-[var(--bg-secondary)] rounded-lg transition-colors"
            >
              <X className="w-5 h-5 text-[var(--text-secondary)]" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {/* Download Template */}
          <div className="p-4 bg-[var(--color-info)]/10 border border-[var(--color-info)]/30 rounded-lg">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <h3 className="text-sm font-semibold text-[var(--text-primary)] mb-1">
                  ¿Primera vez importando?
                </h3>
                <p className="text-sm text-[var(--text-secondary)]">
                  Descarga nuestra plantilla CSV con ejemplos y formato correcto
                </p>
              </div>
              <button
                onClick={downloadTemplate}
                className="flex items-center gap-2 px-4 py-2 bg-[var(--color-info)] text-white rounded-lg hover:bg-[var(--color-info)]/90 transition-colors text-sm font-medium"
              >
                <Download className="w-4 h-4" />
                Descargar Plantilla
              </button>
            </div>
          </div>

          {/* File Upload */}
          {!file && (
            <div className="border-2 border-dashed border-[var(--border-secondary)] rounded-lg p-12 text-center">
              <Upload className="w-16 h-16 text-[var(--text-tertiary)] mx-auto mb-4" />
              <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
                Selecciona un archivo CSV
              </h3>
              <p className="text-sm text-[var(--text-secondary)] mb-4">
                Arrastra y suelta o haz clic para seleccionar
              </p>
              <label className="inline-flex items-center gap-2 px-6 py-3 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] cursor-pointer transition-colors">
                <FileText className="w-5 h-5" />
                Seleccionar Archivo
                <input
                  type="file"
                  accept=".csv"
                  onChange={handleFileSelect}
                  className="hidden"
                />
              </label>
            </div>
          )}

          {/* Preview */}
          {file && parsedSuppliers.length > 0 && (
            <div className="space-y-4">
              {/* Stats */}
              <div className="grid grid-cols-3 gap-4">
                <div className="p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-secondary)]">
                  <div className="flex items-center gap-2 mb-1">
                    <FileText className="w-4 h-4 text-[var(--text-tertiary)]" />
                    <span className="text-xs text-[var(--text-tertiary)]">Total</span>
                  </div>
                  <p className="text-2xl font-bold text-[var(--text-primary)]">{parsedSuppliers.length}</p>
                </div>

                <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                  <div className="flex items-center gap-2 mb-1">
                    <CheckCircle2 className="w-4 h-4 text-green-600" />
                    <span className="text-xs text-green-600">Válidos</span>
                  </div>
                  <p className="text-2xl font-bold text-green-700">{validCount}</p>
                </div>

                <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                  <div className="flex items-center gap-2 mb-1">
                    <AlertCircle className="w-4 h-4 text-red-600" />
                    <span className="text-xs text-red-600">Con Errores</span>
                  </div>
                  <p className="text-2xl font-bold text-red-700">{invalidCount}</p>
                </div>
              </div>

              {/* List */}
              <div className="space-y-2 max-h-96 overflow-y-auto">
                {parsedSuppliers.map((supplier, index) => (
                  <div
                    key={index}
                    className={`p-4 rounded-lg border ${
                      supplier.isValid
                        ? 'bg-green-50 border-green-200'
                        : 'bg-red-50 border-red-200'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          {supplier.isValid ? (
                            <CheckCircle2 className="w-4 h-4 text-green-600" />
                          ) : (
                            <AlertCircle className="w-4 h-4 text-red-600" />
                          )}
                          <span className="font-medium text-sm text-[var(--text-primary)]">
                            Fila {supplier.row}: {supplier.data.name || 'Sin nombre'}
                          </span>
                        </div>
                        {supplier.data.supplier_type && (
                          <p className="text-xs text-[var(--text-secondary)] ml-6">
                            Tipo: {supplier.data.supplier_type}
                          </p>
                        )}
                        {supplier.errors.length > 0 && (
                          <div className="ml-6 mt-1 space-y-1">
                            {supplier.errors.map((error, i) => (
                              <p key={i} className="text-xs text-red-600">• {error}</p>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Success Message */}
          {importStatus === 'success' && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center gap-2 text-green-700">
                <CheckCircle2 className="w-5 h-5" />
                <span className="font-medium">¡Importación exitosa! {validCount} proveedores importados</span>
              </div>
            </div>
          )}

          {/* Error Message */}
          {importStatus === 'error' && (
            <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
              <div className="flex items-center gap-2 text-red-700">
                <AlertCircle className="w-5 h-5" />
                <span className="font-medium">Error al importar proveedores. Inténtalo de nuevo.</span>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-[var(--border-secondary)] bg-[var(--bg-secondary)] flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm text-[var(--text-tertiary)]">
            {file && (
              <>
                <Users className="w-4 h-4" />
                <span>{validCount} proveedores listos para importar</span>
              </>
            )}
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={handleClose}
              disabled={isProcessing}
              className="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-primary)] rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors disabled:opacity-50"
            >
              Cancelar
            </button>
            {file && validCount > 0 && importStatus === 'idle' && (
              <button
                onClick={handleImport}
                disabled={isProcessing}
                className="px-6 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] transition-colors disabled:opacity-50 flex items-center gap-2"
              >
                {isProcessing ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                    Importando...
                  </>
                ) : (
                  <>
                    <Upload className="w-4 h-4" />
                    Importar {validCount} Proveedores
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
