const fields = [
  { fieldName: 'KorName', dataType: 'text' },
  { fieldName: 'Gender', dataType: 'text' },
  { fieldName: 'Age', dataType: 'number' },
  { fieldName: 'Phone', dataType: 'text' },
  { fieldName: 'ProductId', dataType: 'text' },
  { fieldName: 'KorCountry', dataType: 'text' },
  { fieldName: 'OrderDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'CardNumber', dataType: 'text' },
  { fieldName: 'Monetary', dataType: 'text' },
  { fieldName: 'StartDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'EndDate', dataType: 'datetime', datetimeFormat: 'yyyy-MM-dd', amText: 'AM', pmText: 'PM' },
  { fieldName: 'ToMonth', dataType: 'number' },
  { fieldName: 'Month', dataType: 'number' },
  { fieldName: 'Year', dataType: 'number' },
  { fieldName: 'InterestRate', dataType: 'number' },
  { fieldName: 'SaveCost', dataType: 'number' },
  { fieldName: 'SaveMaturity', dataType: 'number' },
  { fieldName: 'CurrentSave', dataType: 'number' }
];

const columns = [
  { name: 'KorName', fieldName: 'KorName', width: '60', header: { text: 'Name' }, renderer: { type: 'text' } },
  { name: 'Gender', fieldName: 'Gender', width: '40', header: { text: 'Gender' }, renderer: { type: 'text' } },
  { name: 'Age', fieldName: 'Age', width: '40', header: { text: 'Age' }, renderer: { type: 'text' } },
  { name: 'Phone', fieldName: 'Phone', width: '100', header: { text: 'Phone' }, renderer: { type: 'text' } },
  { name: 'ProductId', fieldName: 'ProductId', width: '120', header: { text: 'Product ID' }, renderer: { type: 'text' } },
  { name: 'KorCountry', fieldName: 'KorCountry', width: '100', header: { text: 'Investment Country' }, renderer: { type: 'text' } },
  { name: 'OrderDate', fieldName: 'OrderDate', width: '100', header: { text: 'Order Date' } },
  { name: 'CardNumber', fieldName: 'CardNumber', width: '140', header: { text: 'Card Number' }, renderer: { type: 'text' } },
  { name: 'Monetary', fieldName: 'Monetary', width: '40', header: { text: 'Currency' }, renderer: { type: 'text' } },
  { name: 'StartDate', fieldName: 'StartDate', width: '100', header: { text: 'First Payment Date' } },
  { name: 'EndDate', fieldName: 'EndDate', width: '100', header: { text: 'End Date' } },
  { name: 'ToMonth', fieldName: 'ToMonth', width: '40', header: { text: 'Payment Count' } },
  { name: 'Month', fieldName: 'Month', width: '40', header: { text: 'Remaining Count' } },
  { name: 'InterestRate', fieldName: 'InterestRate', width: '40', numberFormat: '0.00', header: { text: 'Interest Rate' } },
  { name: 'SaveCost', fieldName: 'SaveCost', width: '80', numberFormat: '#,##0', header: { text: 'Payment Amount' } },
  { name: 'SaveMaturity', fieldName: 'SaveMaturity', width: '80', numberFormat: '#,##0', header: { text: 'Maturity Amount' } },
  { name: 'CurrentSave', fieldName: 'CurrentSave', width: '80', numberFormat: '#,##0', header: { text: 'Current Balance' } }
];

const { gridView, dataProvider } = RealGrid.createGrid('realgrid', {
  columns,
  header: {
    height: 40
  },
  display: {
    rowHeight: 36,
    emptyMessage: 'No data to display.'
  },
  edit: {
    insertable: true,
    appendable: true
  },
  footer: {
    height: 40
  },
  stateBar: {
    width: 16
  },
  onInitialized: (grid) => {
    fetch('/data/en/simple_data.json')
      .then(response => response.json())
      .then(data => {
        grid.getDataSource().setRows(data);
      });
  }
}, {
  fields
});

window.gridView = gridView;
window.dataProvider = dataProvider;

window.excelExport = function() {
  gridView.exportGrid({
    type: 'excel',
    target: 'local',
    fileName: 'gridExportSample.xlsx',
    footer: 'hidden',
    done: function () {
      alert('done excel export');
    }
  });
};

window.gridClear = function() {
  dataProvider.clearRows();
};

window.fixdata = function(data) {
  var o = '', l = 0, w = 10240;
  for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
  o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
  return o;
};

window.handleXlsFile = function(e) {
  const files = e.target.files;
  if (files.length === 0) return;

  const file = files[0];
  const reader = new FileReader();

  reader.onload = function (e) {
    const data = e.target.result;
    const arr = window.fixdata(data);
    const workbook = XLSX.read(btoa(arr), { type: 'base64', cellText: true, cellDates: true });
    window.processWorkbook(workbook);
  };

  reader.readAsArrayBuffer(file);
};

window.processWorkbook = function(wb) {
  const output = window.toJson(wb);
  const sheetNames = Object.keys(output);

  if (sheetNames.length > 0) {
    const colsObj = output[sheetNames[0]][0];
    if (colsObj) {
      const rawData = output[sheetNames[0]];
      const mappedData = rawData.map(item => {
        return {
          KorName: item.Name,
          Gender: item.Gender,
          Age: item.Age,
          Phone: item.Phone,
          ProductId: item.Product ID,
          KorCountry: item.Investment Country,
          OrderDate: item.Order Date,
          CardNumber: item.Card Number,
          Monetary: item.Currency,
          StartDate: item.First Payment Date,
          EndDate: item.End Date,
          ToMonth: item['Payment Count'],
          Month: item['Remaining Count'],
          InterestRate: item.Interest Rate,
          SaveCost: item.Payment Amount,
          SaveMaturity: item.Maturity Amount
        };
      });
      dataProvider.fillJsonData(mappedData, {});
    }
  }
};

window.toJson = function(workbook) {
  const result = {};
  workbook.SheetNames.forEach(function (sheetName) {
    const roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName], { rawNumbers: true, raw: false });
    if (roa.length > 0) {
      result[sheetName] = roa;
    }
  });
  return result;
};

// DOM is already ready when code runs in runner.html, so setTimeout is used
setTimeout(function() {
  const fileInput = document.getElementById('xlf');
  if (fileInput) {
    fileInput.addEventListener('change', window.handleXlsFile);
    console.log('Excel import event listener registered');
  } else {
    console.error('File input not found');
  }
}, 100);