import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import { importService, accountService, categoryService, costCenterService } from '../services/api';

const ImportTransactions = () => {
  const { t } = useTranslation();
  
  // Steps: 1=Upload, 2=Configure, 3=Map Columns, 4=Import
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  
  // File data
  const [uploadedFile, setUploadedFile] = useState(null);
  const [preview, setPreview] = useState(null);
  
  // Configuration
  const [headerRow, setHeaderRow] = useState(0);
  const [dataStartRow, setDataStartRow] = useState(1);
  const [dateFormat, setDateFormat] = useState('d/m/Y');
  const [decimalSeparator, setDecimalSeparator] = useState(',');
  const [thousandsSeparator, setThousandsSeparator] = useState('.');
  
  // Headers and mapping
  const [headers, setHeaders] = useState([]);
  const [suggestions, setSuggestions] = useState({});
  const [columnMappings, setColumnMappings] = useState({});
  
  // Import options
  const [accountId, setAccountId] = useState('');
  const [categoryId, setCategoryId] = useState('');
  const [costCenterId, setCostCenterId] = useState('');
  const [saveMapping, setSaveMapping] = useState(false);
  const [mappingName, setMappingName] = useState('');
  const [bankName, setBankName] = useState('');
  
  // Data lists
  const [accounts, setAccounts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [costCenters, setCostCenters] = useState([]);
  const [savedMappings, setSavedMappings] = useState([]);
  const [importHistory, setImportHistory] = useState([]);
  const [selectedMapping, setSelectedMapping] = useState(null);
  
  // Field definitions
  const [fieldDefinitions, setFieldDefinitions] = useState({});
  const [dateFormats, setDateFormats] = useState({});
  
  // Import result
  const [importResult, setImportResult] = useState(null);

  // Load initial data
  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    try {
      const [accountsRes, categoriesRes, costCentersRes, mappingsRes, historyRes, fieldsRes] = await Promise.all([
        accountService.getAll(),
        categoryService.getAll(),
        costCenterService.getAll(),
        importService.getMappings(),
        importService.getHistory(),
        importService.getFields(),
      ]);
      
      setAccounts(Array.isArray(accountsRes) ? accountsRes : (accountsRes.data || []));
      setCategories(Array.isArray(categoriesRes) ? categoriesRes : (categoriesRes.data || []));
      setCostCenters(Array.isArray(costCentersRes) ? costCentersRes : (costCentersRes.data || []));
      setSavedMappings(Array.isArray(mappingsRes) ? mappingsRes : (mappingsRes.data || []));
      setImportHistory(Array.isArray(historyRes) ? historyRes : (historyRes.data || []));
      
      if (fieldsRes.data) {
        setFieldDefinitions(fieldsRes.data.fields || {});
        setDateFormats(fieldsRes.data.date_formats || {});
      }
    } catch (err) {
      console.error('Error loading initial data:', err);
    }
  };

  // File upload handler
  const onDrop = useCallback(async (acceptedFiles) => {
    if (acceptedFiles.length === 0) return;
    
    const file = acceptedFiles[0];
    setError('');
    setLoading(true);
    
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await importService.upload(formData);
      
      if (response.success && response.data) {
        setUploadedFile(response.data);
        setPreview(response.data.preview);
        
        // Auto-detect header row
        if (response.data.preview?.preview) {
          const previewRows = response.data.preview.preview;
          // Find first row with most non-empty cells
          let bestRow = 0;
          let maxCells = 0;
          previewRows.forEach((row, idx) => {
            const nonEmpty = row.data.filter(c => c !== null && c !== '').length;
            if (nonEmpty > maxCells) {
              maxCells = nonEmpty;
              bestRow = idx;
            }
          });
          setHeaderRow(bestRow);
          setDataStartRow(bestRow + 1);
        }
        
        setStep(2);
      } else {
        setError(response.message || t('import.uploadError'));
      }
    } catch (err) {
      setError(err.response?.data?.message || t('import.uploadError'));
    } finally {
      setLoading(false);
    }
  }, [t]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
      'application/vnd.ms-excel': ['.xls'],
      'text/csv': ['.csv'],
      'application/x-ofx': ['.ofx'],
      'application/pdf': ['.pdf'],
    },
    maxFiles: 1,
    maxSize: 10 * 1024 * 1024, // 10MB
  });

  // Load headers when configuration changes
  const loadHeaders = async () => {
    if (!uploadedFile?.temp_file) return;
    
    setLoading(true);
    setError('');
    
    try {
      const response = await importService.getHeaders({
        temp_file: uploadedFile.temp_file,
        header_row: headerRow,
      });
      
      if (response.success && response.data) {
        setHeaders(response.data.headers || []);
        setSuggestions(response.data.suggestions || {});
        
        // Apply suggestions to mappings
        const newMappings = {};
        Object.keys(response.data.suggestions || {}).forEach(field => {
          newMappings[field] = response.data.suggestions[field];
        });
        setColumnMappings(newMappings);
      }
    } catch (err) {
      setError(err.response?.data?.message || t('import.headerError'));
    } finally {
      setLoading(false);
    }
  };

  // Go to mapping step
  const goToMapping = async () => {
    await loadHeaders();
    setStep(3);
  };

  // Apply saved mapping
  const applySavedMapping = (mapping) => {
    setSelectedMapping(mapping);
    setHeaderRow(mapping.header_row);
    setDataStartRow(mapping.data_start_row);
    setDateFormat(mapping.date_format);
    setDecimalSeparator(mapping.decimal_separator);
    setThousandsSeparator(mapping.thousands_separator);
    setColumnMappings(mapping.column_mappings);
    setAccountId(mapping.default_account_id || '');
    setCategoryId(mapping.default_category_id || '');
    setCostCenterId(mapping.default_cost_center_id || '');
    setBankName(mapping.bank_name || '');
    setMappingName(mapping.name);
  };

  // Update column mapping
  const updateMapping = (field, columnIndex, add = true) => {
    setColumnMappings(prev => {
      const current = prev[field] || { columns: [], concat_separator: ' ' };
      let newColumns;
      
      if (add) {
        if (!current.columns.includes(columnIndex)) {
          newColumns = [...current.columns, columnIndex];
        } else {
          newColumns = current.columns;
        }
      } else {
        newColumns = current.columns.filter(c => c !== columnIndex);
      }
      
      return {
        ...prev,
        [field]: {
          ...current,
          columns: newColumns,
        },
      };
    });
  };

  // Update concat separator
  const updateConcatSeparator = (field, separator) => {
    setColumnMappings(prev => ({
      ...prev,
      [field]: {
        ...(prev[field] || { columns: [] }),
        concat_separator: separator,
      },
    }));
  };

  // Remove field mapping
  const removeFieldMapping = (field) => {
    setColumnMappings(prev => {
      const newMappings = { ...prev };
      delete newMappings[field];
      return newMappings;
    });
  };

  // Execute import
  const executeImport = async () => {
    setLoading(true);
    setError('');
    setSuccess('');
    
    try {
      const payload = {
        temp_file: uploadedFile.temp_file,
        column_mappings: columnMappings,
        header_row: headerRow,
        data_start_row: dataStartRow,
        date_format: dateFormat,
        decimal_separator: decimalSeparator,
        thousands_separator: thousandsSeparator,
        account_id: accountId || null,
        category_id: categoryId || null,
        cost_center_id: costCenterId || null,
        save_mapping: saveMapping,
        mapping_name: saveMapping ? mappingName : null,
        bank_name: bankName || null,
      };
      
      if (selectedMapping?.id) {
        payload.mapping_id = selectedMapping.id;
      }
      
      const response = await importService.process(payload);
      
      if (response.success) {
        setImportResult(response.data);
        setSuccess(response.message);
        setStep(4);
        
        // Reload history
        const historyRes = await importService.getHistory();
        setImportHistory(Array.isArray(historyRes) ? historyRes : (historyRes.data || []));
      } else {
        setError(response.message || t('import.importError'));
      }
    } catch (err) {
      setError(err.response?.data?.message || t('import.importError'));
    } finally {
      setLoading(false);
    }
  };

  // Reset to start
  const resetImport = () => {
    setStep(1);
    setUploadedFile(null);
    setPreview(null);
    setHeaders([]);
    setSuggestions({});
    setColumnMappings({});
    setSelectedMapping(null);
    setImportResult(null);
    setError('');
    setSuccess('');
  };

  // Render step indicators
  const renderStepIndicator = () => (
    <div className="d-flex justify-content-center mb-4">
      <div className="d-flex align-items-center">
        {[1, 2, 3, 4].map((s, idx) => (
          <React.Fragment key={s}>
            <div 
              className={`rounded-circle d-flex align-items-center justify-content-center ${
                step >= s ? 'bg-primary text-white' : 'bg-secondary text-white'
              }`}
              style={{ width: 36, height: 36, cursor: step > s ? 'pointer' : 'default' }}
              onClick={() => step > s && setStep(s)}
            >
              {s}
            </div>
            {idx < 3 && (
              <div 
                className={`mx-2 ${step > s ? 'bg-primary' : 'bg-secondary'}`}
                style={{ width: 60, height: 3 }}
              />
            )}
          </React.Fragment>
        ))}
      </div>
    </div>
  );

  // Render Step 1: Upload
  const renderUploadStep = () => (
    <div className="card">
      <div className="card-header">
        <h5 className="mb-0">
          <i className="bi bi-cloud-upload me-2"></i>
          {t('import.step1Title')}
        </h5>
      </div>
      <div className="card-body">
        {/* Saved Mappings */}
        {savedMappings.length > 0 && (
          <div className="mb-4">
            <label className="form-label">{t('import.useSavedMapping')}</label>
            <select 
              className="form-select"
              value={selectedMapping?.id || ''}
              onChange={(e) => {
                const mapping = savedMappings.find(m => m.id === parseInt(e.target.value));
                if (mapping) applySavedMapping(mapping);
                else setSelectedMapping(null);
              }}
            >
              <option value="">{t('import.newMapping')}</option>
              {savedMappings.map(m => (
                <option key={m.id} value={m.id}>{m.name} ({m.bank_name || m.file_type})</option>
              ))}
            </select>
          </div>
        )}
        
        {/* Dropzone */}
        <div 
          {...getRootProps()} 
          className={`border border-2 border-dashed rounded p-5 text-center ${
            isDragActive ? 'border-primary bg-primary bg-opacity-10' : 'border-secondary'
          }`}
          style={{ cursor: 'pointer' }}
        >
          <input {...getInputProps()} />
          <i className="bi bi-file-earmark-arrow-up display-1 text-muted"></i>
          <p className="mt-3 mb-1">
            {isDragActive ? t('import.dropHere') : t('import.dragDrop')}
          </p>
          <small className="text-muted">
            {t('import.supportedFormats')}: XLSX, XLS, CSV, OFX, PDF
          </small>
        </div>
        
        {/* Recent Imports */}
        {importHistory.length > 0 && (
          <div className="mt-4">
            <h6>{t('import.recentImports')}</h6>
            <div className="table-responsive">
              <table className="table table-sm">
                <thead>
                  <tr>
                    <th>{t('import.date')}</th>
                    <th>{t('import.file')}</th>
                    <th>{t('import.status')}</th>
                    <th>{t('import.imported')}</th>
                  </tr>
                </thead>
                <tbody>
                  {importHistory.slice(0, 5).map(log => (
                    <tr key={log.id}>
                      <td>{new Date(log.created_at).toLocaleDateString()}</td>
                      <td>{log.original_filename}</td>
                      <td>
                        <span className={`badge bg-${
                          log.status === 'completed' ? 'success' : 
                          log.status === 'failed' ? 'danger' : 'warning'
                        }`}>
                          {log.status}
                        </span>
                      </td>
                      <td>{log.imported_rows} / {log.total_rows}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );

  // Render Step 2: Configure
  const renderConfigureStep = () => (
    <div className="card">
      <div className="card-header">
        <h5 className="mb-0">
          <i className="bi bi-gear me-2"></i>
          {t('import.step2Title')}
        </h5>
      </div>
      <div className="card-body">
        {/* File Info */}
        <div className="alert alert-info">
          <i className="bi bi-file-earmark me-2"></i>
          <strong>{uploadedFile?.original_name}</strong>
          <span className="ms-2">({(uploadedFile?.size / 1024).toFixed(1)} KB)</span>
        </div>
        
        <div className="row g-3">
          <div className="col-md-6">
            <label className="form-label">{t('import.headerRow')}</label>
            <select 
              className="form-select"
              value={headerRow}
              onChange={(e) => setHeaderRow(parseInt(e.target.value))}
            >
              {preview?.preview?.map((row, idx) => (
                <option key={idx} value={idx}>
                  {t('import.row')} {idx}: {row.data.filter(c => c).slice(0, 3).join(', ')}...
                </option>
              ))}
            </select>
          </div>
          
          <div className="col-md-6">
            <label className="form-label">{t('import.dataStartRow')}</label>
            <select 
              className="form-select"
              value={dataStartRow}
              onChange={(e) => setDataStartRow(parseInt(e.target.value))}
            >
              {preview?.preview?.map((row, idx) => (
                <option key={idx} value={idx}>
                  {t('import.row')} {idx}: {row.data.filter(c => c).slice(0, 3).join(', ')}...
                </option>
              ))}
            </select>
          </div>
          
          <div className="col-md-4">
            <label className="form-label">{t('import.dateFormat')}</label>
            <select 
              className="form-select"
              value={dateFormat}
              onChange={(e) => setDateFormat(e.target.value)}
            >
              {Object.entries(dateFormats).map(([format, label]) => (
                <option key={format} value={format}>{label}</option>
              ))}
            </select>
          </div>
          
          <div className="col-md-4">
            <label className="form-label">{t('import.decimalSeparator')}</label>
            <select 
              className="form-select"
              value={decimalSeparator}
              onChange={(e) => setDecimalSeparator(e.target.value)}
            >
              <option value=",">{t('import.comma')} (,)</option>
              <option value=".">{t('import.dot')} (.)</option>
            </select>
          </div>
          
          <div className="col-md-4">
            <label className="form-label">{t('import.thousandsSeparator')}</label>
            <select 
              className="form-select"
              value={thousandsSeparator}
              onChange={(e) => setThousandsSeparator(e.target.value)}
            >
              <option value=".">{t('import.dot')} (.)</option>
              <option value=",">{t('import.comma')} (,)</option>
              <option value=" ">{t('import.space')}</option>
              <option value="">{t('import.none')}</option>
            </select>
          </div>
        </div>
        
        {/* Preview Table */}
        <div className="mt-4">
          <h6>{t('import.preview')}</h6>
          <div className="table-responsive" style={{ maxHeight: 300, overflow: 'auto' }}>
            <table className="table table-sm table-bordered">
              <thead className="table-light sticky-top">
                <tr>
                  <th>#</th>
                  {preview?.preview?.[0]?.data.map((_, idx) => (
                    <th key={idx}>{t('import.col')} {idx}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {preview?.preview?.map((row, rowIdx) => (
                  <tr 
                    key={rowIdx}
                    className={
                      rowIdx === headerRow ? 'table-primary' : 
                      rowIdx >= dataStartRow ? '' : 'table-secondary'
                    }
                  >
                    <td>{rowIdx}</td>
                    {row.data.map((cell, cellIdx) => (
                      <td key={cellIdx}>
                        {cell !== null && cell !== '' ? String(cell).substring(0, 30) : '-'}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <small className="text-muted">
            <span className="badge bg-primary me-2">{t('import.headerRowLabel')}</span>
            <span className="badge bg-secondary me-2">{t('import.skippedRows')}</span>
            {t('import.dataRows')}
          </small>
        </div>
        
        <div className="d-flex justify-content-between mt-4">
          <button className="btn btn-secondary" onClick={resetImport}>
            <i className="bi bi-arrow-left me-2"></i>
            {t('common.back')}
          </button>
          <button className="btn btn-primary" onClick={goToMapping} disabled={loading}>
            {loading ? (
              <span className="spinner-border spinner-border-sm me-2"></span>
            ) : (
              <i className="bi bi-arrow-right me-2"></i>
            )}
            {t('common.next')}
          </button>
        </div>
      </div>
    </div>
  );

  // Render Step 3: Map Columns
  const renderMappingStep = () => (
    <div className="card">
      <div className="card-header">
        <h5 className="mb-0">
          <i className="bi bi-diagram-3 me-2"></i>
          {t('import.step3Title')}
        </h5>
      </div>
      <div className="card-body">
        <div className="row">
          {/* Column Mappings */}
          <div className="col-lg-8">
            <h6 className="mb-3">{t('import.mapColumns')}</h6>
            
            {Object.entries(fieldDefinitions).map(([field, config]) => (
              <div key={field} className="card mb-2">
                <div className="card-body py-2">
                  <div className="row align-items-center">
                    <div className="col-md-3">
                      <strong>{config.label}</strong>
                      {config.required && <span className="text-danger ms-1">*</span>}
                      <br/>
                      <small className="text-muted">{config.type}</small>
                    </div>
                    <div className="col-md-6">
                      <select
                        className="form-select form-select-sm"
                        value={columnMappings[field]?.columns?.[0] ?? ''}
                        onChange={(e) => {
                          const val = e.target.value;
                          if (val === '') {
                            removeFieldMapping(field);
                          } else {
                            setColumnMappings(prev => ({
                              ...prev,
                              [field]: {
                                columns: [parseInt(val)],
                                concat_separator: prev[field]?.concat_separator || ' ',
                              }
                            }));
                          }
                        }}
                      >
                        <option value="">{t('import.selectColumn')}</option>
                        {headers.map((header, idx) => (
                          <option key={idx} value={idx}>
                            {idx}: {header || `(${t('import.empty')})`}
                          </option>
                        ))}
                      </select>
                      
                      {/* Additional columns for concatenation */}
                      {columnMappings[field]?.columns?.length > 0 && (
                        <div className="mt-1">
                          <small className="text-muted">{t('import.concatenateWith')}:</small>
                          <div className="d-flex align-items-center gap-2">
                            <select
                              className="form-select form-select-sm"
                              style={{ width: 'auto' }}
                              value=""
                              onChange={(e) => {
                                if (e.target.value) {
                                  updateMapping(field, parseInt(e.target.value), true);
                                }
                              }}
                            >
                              <option value="">{t('import.addColumn')}</option>
                              {headers.map((header, idx) => (
                                !columnMappings[field]?.columns?.includes(idx) && (
                                  <option key={idx} value={idx}>
                                    {idx}: {header || `(${t('import.empty')})`}
                                  </option>
                                )
                              ))}
                            </select>
                            
                            {columnMappings[field]?.columns?.length > 1 && (
                              <input
                                type="text"
                                className="form-control form-control-sm"
                                style={{ width: 80 }}
                                placeholder={t('import.separator')}
                                value={columnMappings[field]?.concat_separator || ''}
                                onChange={(e) => updateConcatSeparator(field, e.target.value)}
                              />
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                    <div className="col-md-3">
                      {columnMappings[field]?.columns?.map((colIdx, i) => (
                        <span key={colIdx} className="badge bg-primary me-1">
                          {headers[colIdx] || `Col ${colIdx}`}
                          {columnMappings[field].columns.length > 1 && (
                            <button
                              type="button"
                              className="btn-close btn-close-white ms-1"
                              style={{ fontSize: '0.6em' }}
                              onClick={() => updateMapping(field, colIdx, false)}
                            />
                          )}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
          
          {/* Import Options */}
          <div className="col-lg-4">
            <h6 className="mb-3">{t('import.importOptions')}</h6>
            
            <div className="mb-3">
              <label className="form-label">{t('import.defaultAccount')}</label>
              <select
                className="form-select"
                value={accountId}
                onChange={(e) => setAccountId(e.target.value)}
              >
                <option value="">{t('import.selectAccount')}</option>
                {accounts.map(acc => (
                  <option key={acc.id} value={acc.id}>{acc.name}</option>
                ))}
              </select>
            </div>
            
            <div className="mb-3">
              <label className="form-label">{t('import.defaultCategory')}</label>
              <select
                className="form-select"
                value={categoryId}
                onChange={(e) => setCategoryId(e.target.value)}
              >
                <option value="">{t('import.selectCategory')}</option>
                {categories.map(cat => (
                  <option key={cat.id} value={cat.id}>{cat.name}</option>
                ))}
              </select>
            </div>
            
            <div className="mb-3">
              <label className="form-label">{t('import.defaultCostCenter')}</label>
              <select
                className="form-select"
                value={costCenterId}
                onChange={(e) => setCostCenterId(e.target.value)}
              >
                <option value="">{t('import.selectCostCenter')}</option>
                {costCenters.map(cc => (
                  <option key={cc.id} value={cc.id}>{cc.name}</option>
                ))}
              </select>
            </div>
            
            <hr/>
            
            <div className="form-check mb-3">
              <input
                type="checkbox"
                className="form-check-input"
                id="saveMapping"
                checked={saveMapping}
                onChange={(e) => setSaveMapping(e.target.checked)}
              />
              <label className="form-check-label" htmlFor="saveMapping">
                {t('import.saveMapping')}
              </label>
            </div>
            
            {saveMapping && (
              <>
                <div className="mb-3">
                  <label className="form-label">{t('import.mappingName')}</label>
                  <input
                    type="text"
                    className="form-control"
                    value={mappingName}
                    onChange={(e) => setMappingName(e.target.value)}
                    placeholder={t('import.mappingNamePlaceholder')}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">{t('import.bankName')}</label>
                  <input
                    type="text"
                    className="form-control"
                    value={bankName}
                    onChange={(e) => setBankName(e.target.value)}
                    placeholder={t('import.bankNamePlaceholder')}
                  />
                </div>
              </>
            )}
          </div>
        </div>
        
        <div className="d-flex justify-content-between mt-4">
          <button className="btn btn-secondary" onClick={() => setStep(2)}>
            <i className="bi bi-arrow-left me-2"></i>
            {t('common.back')}
          </button>
          <button 
            className="btn btn-success" 
            onClick={executeImport} 
            disabled={loading || !columnMappings.effective_date || !columnMappings.amount}
          >
            {loading ? (
              <span className="spinner-border spinner-border-sm me-2"></span>
            ) : (
              <i className="bi bi-check-circle me-2"></i>
            )}
            {t('import.executeImport')}
          </button>
        </div>
      </div>
    </div>
  );

  // Render Step 4: Result
  const renderResultStep = () => (
    <div className="card">
      <div className="card-header bg-success text-white">
        <h5 className="mb-0">
          <i className="bi bi-check-circle me-2"></i>
          {t('import.step4Title')}
        </h5>
      </div>
      <div className="card-body text-center">
        <i className="bi bi-check-circle-fill text-success display-1"></i>
        <h4 className="mt-3">{t('import.importComplete')}</h4>
        
        {importResult?.import_log && (
          <div className="row justify-content-center mt-4">
            <div className="col-md-6">
              <div className="card">
                <div className="card-body">
                  <div className="row text-center">
                    <div className="col-4">
                      <h3 className="text-success">{importResult.import_log.imported_rows}</h3>
                      <small>{t('import.imported')}</small>
                    </div>
                    <div className="col-4">
                      <h3 className="text-warning">{importResult.import_log.skipped_rows}</h3>
                      <small>{t('import.skipped')}</small>
                    </div>
                    <div className="col-4">
                      <h3 className="text-danger">{importResult.import_log.error_rows}</h3>
                      <small>{t('import.errors')}</small>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
        
        <div className="mt-4">
          <button className="btn btn-primary me-2" onClick={resetImport}>
            <i className="bi bi-plus-circle me-2"></i>
            {t('import.importMore')}
          </button>
          <a href="/transactions" className="btn btn-outline-primary">
            <i className="bi bi-list me-2"></i>
            {t('import.viewTransactions')}
          </a>
        </div>
      </div>
    </div>
  );

  return (
    <div className="container-fluid py-4">
      <div className="row mb-4">
        <div className="col">
          <h2>
            <i className="bi bi-file-earmark-arrow-up me-2"></i>
            {t('import.title')}
          </h2>
          <p className="text-muted">{t('import.subtitle')}</p>
        </div>
      </div>
      
      {renderStepIndicator()}
      
      {error && (
        <div className="alert alert-danger alert-dismissible fade show">
          <i className="bi bi-exclamation-triangle me-2"></i>
          {error}
          <button type="button" className="btn-close" onClick={() => setError('')}></button>
        </div>
      )}
      
      {success && (
        <div className="alert alert-success alert-dismissible fade show">
          <i className="bi bi-check-circle me-2"></i>
          {success}
          <button type="button" className="btn-close" onClick={() => setSuccess('')}></button>
        </div>
      )}
      
      {loading && step === 1 && (
        <div className="text-center py-5">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
          <p className="mt-2">{t('import.processing')}</p>
        </div>
      )}
      
      {step === 1 && !loading && renderUploadStep()}
      {step === 2 && renderConfigureStep()}
      {step === 3 && renderMappingStep()}
      {step === 4 && renderResultStep()}
    </div>
  );
};

export default ImportTransactions;
