import * as XLSX from 'xlsx';

const validateName = (name: string) => {
  if ((name + "").length > 2) {
    return true;
  }
  return false;
}

function createDiagonalPattern1(color: string) {
  // create a 10x10 px canvas for the pattern's base shape
  let shape = document.createElement('canvas')
  shape.width = 10
  shape.height = 10
  // get the context for drawing
  let c = shape.getContext('2d')
  // draw 1st line of the shape 
  c!.strokeStyle = color
  c!.lineWidth = 3
  c!.beginPath()
  c!.moveTo(2, 0)
  c!.lineTo(10, 8)
  c!.stroke()
  // draw 2nd line of the shape 
  c!.beginPath()
  c!.moveTo(2, 10)
  c!.lineTo(0, 8)
  c!.stroke()
  // create the pattern from the shape
  return c!.createPattern(shape, 'repeat')
}

// function createDiagonalPattern2(color: string) {
//   let shape = document.createElement('canvas')
//   shape.width = 10
//   shape.height = 10
//   // get the context for drawing
//   let c = shape.getContext('2d')
//   // draw 1st line of the shape 
//   c!.beginPath();
//   c!.rect(2, 2, 8, 8)
//   c!.fillStyle = color;
//   c!.fill();
//   // create the pattern from the shape
//   return c!.createPattern(shape, 'repeat')
// }

function createDiagonalPattern2(color: string) {
  // create a 10x10 px canvas for the pattern's base shape
  let shape = document.createElement('canvas')
  shape.width = 10
  shape.height = 10
  // get the context for drawing
  let c = shape.getContext('2d')
  // draw 1st line of the shape 
  c!.beginPath();
  c!.rect(1, 1, 9, 9)
  c!.fillStyle = color;
  c!.fill();
  c!.lineWidth = 1;
  c!.strokeStyle = color;
  c!.stroke();
  // create the pattern from the shape

  // create tick

  //draw tick
  c!.beginPath();
  c!.moveTo(2, 2);
  c!.lineTo(8, 8);
  c!.moveTo(2, 8);
  c!.lineTo(8, 2);
  c!.lineWidth = 2;
  c!.strokeStyle = '#fff';
  c!.stroke();

  return c!.createPattern(shape, 'repeat')
}

function createDiagonalPattern3(color: string) {
  // create a 10x10 px canvas for the pattern's base shape
  let shape = document.createElement('canvas')
  shape.width = 10
  shape.height = 10
  // get the context for drawing
  let c = shape.getContext('2d')
  // draw 1st line of the shape 
  c!.beginPath();
  c!.rect(1, 1, 9, 9)
  c!.fillStyle = color;
  c!.fill();
  c!.lineWidth = 1;
  c!.strokeStyle = color;
  c!.stroke();
  // create the pattern from the shape

  // create tick

  //draw tick
  c!.beginPath();
  c!.moveTo(2, 5);
  c!.lineTo(4, 7);
  c!.lineTo(8, 2);
  c!.lineWidth = 2;
  c!.strokeStyle = '#fff';
  c!.stroke();

  return c!.createPattern(shape, 'repeat')
}

// function createDiagonalPattern3(color: string) {
//   // create a 10x10 px canvas for the pattern's base shape
//   let shape = document.createElement('canvas')
//   shape.width = 14
//   shape.height = 14
//   // get the context for drawing
//   let c = shape.getContext('2d')
//   // draw 1st line of the shape 
//   c!.beginPath();
//   c!.arc(7, 7, 6, 0, 2 * Math.PI, false);
//   c!.fillStyle = color;
//   c!.fill();
//   c!.lineWidth = 1;
//   c!.strokeStyle = color;
//   c!.stroke();
//   // create the pattern from the shape

//   // create tick

//   //draw tick
//   c!.beginPath();
//   c!.moveTo(4,6);
//   c!.lineTo(6,9);
//   c!.lineTo(10,4);
//   c!.lineWidth = 2;
//   c!.strokeStyle = '#fff';
//   c!.stroke();

//   return c!.createPattern(shape, 'repeat')
// }

// function createDiagonalPattern3(color: string) {
//   // create a 10x10 px canvas for the pattern's base shape
//   let shape = document.createElement('canvas')
//   shape.width = 10
//   shape.height = 10
//   // get the context for drawing
//   let c = shape.getContext('2d')
//   // draw 1st line of the shape 
//   c!.beginPath();
//   c!.arc(5, 5, 4, 0, 2 * Math.PI, false);
//   c!.fillStyle = color;
//   c!.fill();
//   c!.lineWidth = 1;
//   c!.strokeStyle = color;
//   c!.stroke();
//   // create the pattern from the shape
//   return c!.createPattern(shape, 'repeat')
// }

const timeSince = (date: number) => {

  var seconds = Math.floor((new Date().getTime() - date) / 1000);

  if (seconds > 0) {

    var interval = seconds / 31536000;

    if (interval > 1) {
      return Math.floor(interval) + " years ago";
    }
    interval = seconds / 2592000;
    if (interval > 1) {
      return Math.floor(interval) + " months ago";
    }
    interval = seconds / 86400;
    if (interval > 1) {
      return Math.floor(interval) + " days ago";
    }
    interval = seconds / 3600;
    if (interval > 1) {
      return Math.floor(interval) + " hours ago";
    }
    interval = seconds / 60;
    if (interval > 1) {
      return Math.floor(interval) + " minutes ago";
    }
    return Math.floor(seconds) + " seconds ago";

  } else {

    var interval = Math.abs(seconds) / 31536000;


    console.log('timesince', seconds);


    console.log('interval year', interval);
    if (interval > 1) {
      return Math.floor(interval) + " years later";
    }
    interval = Math.abs(seconds) / 2592000;
    console.log('interval months', interval);
    if (interval > 1) {
      return Math.floor(interval) + " months later";
    }

    interval = Math.abs(seconds) / 86400;
    console.log('interval days', interval);
    if (interval > 1) {
      return Math.floor(interval) + " days later";
    }

    interval = Math.abs(seconds) / 3600;
    console.log('interval hours', interval);
    if (interval > 1) {
      return Math.floor(interval) + " hours later";
    }
    interval = Math.abs(seconds) / 60;
    if (interval > 1) {
      return Math.floor(interval) + " minutes later";
    }
    return Math.floor(Math.abs(seconds)) + " seconds";

  }
}


function readCookie(key: string) {
  let name = key + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

async function callApi(url: string, data: string, authorization: any) {

  return new Promise((resolve: any) => {

    const jsonData = JSON.stringify(data);
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
      if (xhr != null) {
        if (xhr.readyState === 4) {
          resolve(xhr);
        }
      }
    });
    xhr.open("POST", url);
    xhr.timeout = 1800000;
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    if (authorization != null) {
      xhr.setRequestHeader('Authorization', 'Basic ' + authorization);
    }
    xhr.send(jsonData);

    return xhr;

  })

}


async function callApiPresignedDelete(url: string) {

  return new Promise((resolve: any) => {

    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
      if (xhr != null) {
        if (xhr.readyState === 4) {
          resolve(xhr);
        }
      }
    });
    xhr.open("DELETE", url);
    xhr.timeout = 1800000;
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send(null);

    return xhr;

  })

}

async function callApiPresignedGet(url: string) {

  return new Promise((resolve: any) => {

    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
      if (xhr != null) {
        if (xhr.readyState === 4) {
          resolve(xhr);
        }
      }
    });
    xhr.open("GET", url);
    xhr.timeout = 1800000;
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send(null);

    return xhr;

  })

}

async function callApiPresigned(url: string, data: string) {

  return new Promise((resolve: any) => {

    const jsonData = JSON.stringify(data);
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", () => {
      if (xhr != null) {
        if (xhr.readyState === 4) {
          resolve(xhr);
        }
      }
    });
    xhr.open("PUT", url);
    xhr.timeout = 1800000;
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.send(jsonData);

    return xhr;

  })

}

// function getRandomColor() {
//   var letters = '0123456789ABCDEF';
//   var color = '#';
//   for (var i = 0; i < 6; i++) {
//     color += letters[Math.floor(Math.random() * 16)];
//   }
//   return color;
// }

function hslToHex(h: number, s: number, l: number) {
  s /= 100;
  l /= 100;

  const k = (n: number) => (n + h / 30) % 12;
  const a = s * Math.min(l, 1 - l);
  const f = (n: number) =>
    Math.round(255 * (l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)))));

  return "#" + [f(0), f(8), f(4)]
    .map(x => x.toString(16).padStart(2, "0"))
    .join("");
}

// let idx = 0;

function getRandomColor(idx: number) {
  const h = (idx * 137.508) % 360;
  idx++;

  const s = 70;
  const l = 60;

  return hslToHex(h, s, l);
}

function isInteger(value: string) {
  return /^-?\d+$/.test(value);
}

function clearListeners(old_element: HTMLElement) {
  var new_element = old_element.cloneNode(true);
  old_element.parentNode?.replaceChild(new_element, old_element);
  return new_element;
}

function jsonObjectToHtml(json: any) {

  var html = '';


  for (var i = 0; i < Object.keys(json).length; i++) {
    var key = Object.keys(json)[i];
    html += '<div>';
    html += ('<span style="margin-left: 0px; padding-left: 0px">' + key + ':</span>&nbsp;');
    html += ('<span class="td-body" part="td-head"><sf-i-elastic-text text="' + json[key].replace(/"/g, '') + '" lineSize="6" minLength="10"></sf-i-elastic-text></span>');
    html += '</div>';
  }


  return html;

}

function convertToCSVStats(arr: any[]) {

  if (!arr || arr.length === 0) {
    return "";
  }

  const fieldsArr = Object.keys(arr[0]);
  const array: any[] = [fieldsArr].concat(arr);

  return array.map((it, index) => {

    let strIt = "";

    for (let [i, objkey] of Object.keys(it).entries()) {

      let value: any;

      if (index === 0) {
        value = it[objkey];
      } else {
        value = it[fieldsArr[i]];
      }

      if (value == null) {
        value = "";
      } else if (typeof value === "object") {
        value = JSON.stringify(value);
      } else {
        value = String(value);
      }

      // Escape quotes for CSV
      value = value.replace(/"/g, '""');

      // Wrap in quotes
      strIt += `"${value}"`;

      if (i < Object.keys(it).length - 1) {
        strIt += ",";
      }
    }

    return strIt;

  }).join("\n");
}

function convertToCSV(arr: any[]) {
  const array = [Object.keys(arr[0])].concat(arr)
  let fieldsArr = Object.keys(arr[0]);
  return array.map((it, index) => {
    let strIt = ""
    for (let [i, objkey] of Object.keys(it).entries()) {
      if (index == 0) {
        strIt += "\"" + it[objkey as any].replace(/"/g, "\"\"") + "\""
      } else {
        strIt += "\"" + JSON.stringify(it[fieldsArr[i] as any] ?? "").replace(/"/g, "\"\"") + "\""
      }
      if (i < (Object.keys(it).length - 1)) {
        strIt += ","
      }
    }
    return strIt
  }).join('\n')
}

function parseCsv(csv: string) {
  const re = /(,|\r?\n|\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^,\r\n]*))/gi
  const result: any = [[]]
  let matches: any;
  while ((matches = re.exec(csv))) {
    if (matches[1].length && matches[1] !== ',') result.push([])
    result[result.length - 1].push(
      matches[2] !== undefined ? matches[2].replace(/""/g, '"') : matches[3]
    )
  }
  // console.log('csv arr result', result, result.length);
  let csvResult = arrayToObject(result)
  return csvResult
}
function arrayToObject(csvArray: any) {

  //Take the first line (headers) from the array and remove it from the array.
  const headers = csvArray.shift()

  // Iterate through the rows and reduce each column to an object

  return csvArray.filter((row: any) => {
    console.log('csv object keys lngth', Object.keys(row).length)
    return Object.keys(row).length > 1
  }).map((row: { [x: string]: any; }) => {

    return headers.reduce((acc: any, currentHeader: any, i: string | number) => {
      // console.log('parsing row', row[i], index);
      return ((currentHeader.indexOf('cols_') >= 0 || currentHeader == '') ? acc : ((row[i] != '' && row[i] != null) ? { ...acc, ...{ [currentHeader]: JSON.parse(row[i] == "TRUE" ? "true" : (row[i] == "FALSE" ? "false" : row[i])) } } : acc))
    }, {})
  })
}

function titleCase(str: string) {
  var splitStr = str.toLowerCase().split(' ');
  for (var i = 0; i < splitStr.length; i++) {
    // You do not need to check if i is larger than splitStr length, as your for does that for you
    // Assign it back to the array
    splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
  }
  // Directly return the joined string
  return splitStr.join(' ');
}

function alphabeticalSort(arr: string[]) {
  let arrSorted = arr.sort((a, b) => {
    return a.trim().toLowerCase().localeCompare(b.trim().toLowerCase())
  })
  return arrSorted
}

function percentageString(val: number, valTotal: number) {
  if (valTotal == 0) {
    return ""
  }
  let num = (100 * val) / valTotal
  return " (" + (Math.round((num + Number.EPSILON) * 100) / 100) + "%)"
}

function getCurrentFiscal() {
  let date = new Date()
  if (date.getMonth() < 4) {
    return (date.getFullYear() - 1)
  }
  return date.getFullYear();
}

function getDateTimeStrings(unixTimestamp: number): string {
  // Convert to milliseconds if the timestamp is in seconds
  if (unixTimestamp.toString().length === 10) {
    unixTimestamp *= 1000;
  }

  const date = new Date(unixTimestamp);

  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  };

  const estFormatter = new Intl.DateTimeFormat('en-US', {
    ...options,
    timeZone: 'America/New_York',
  });

  const istFormatter = new Intl.DateTimeFormat('en-IN', {
    ...options,
    timeZone: 'Asia/Kolkata',
  });

  const [estDate, estTime] = estFormatter.format(date).split(', ');
  const [istDate, istTime] = istFormatter.format(date).split(', ');
  return `${estDate} ${estTime} EST, ${istDate} ${istTime} IST`;
}

function getUsermap() {
  let userinfo = JSON.parse(localStorage.getItem('userinfo') ?? "{}");
  let userMapHome = JSON.parse(JSON.parse((userinfo.user.usermap.S).replace(/_QUOTES_/g, "\\\"")));
  return userMapHome;
}

function getUserAdhocCheckTime() {
  let userinfo = JSON.parse(localStorage.getItem('userinfo') ?? "{}");
  let userAdHocCheckTime = (userinfo.adhocCheckTime) + "";
  return userAdHocCheckTime;
}

function putUserAdhocCheckTime(userAdhocCheckTime: number) {
  let userinfo = JSON.parse(localStorage.getItem('userinfo') ?? "{}");
  userinfo.adhocCheckTime = userAdhocCheckTime;
  localStorage.setItem('userinfo', JSON.stringify(userinfo));
  return
}

function getProjectConfigHome() {
  let userinfo = JSON.parse(localStorage.getItem('userinfo') ?? "{}");
  let projectConfigHome = JSON.parse(JSON.parse((userinfo.project.data.value.confighome)));
  return projectConfigHome;
}

function getProjectUsermap() {
  let projectUsermap = JSON.parse((localStorage.getItem('projectusermap') ?? "{}").replace(/_QUOTES_/g, "\\\""));
  return projectUsermap;
}

function setFeatures(features: any) {
  localStorage.setItem('features', JSON.stringify(features))
}
function getFeatures() {
  let features = JSON.parse(localStorage.getItem('features') ?? '["compliances"]')
  return features
}

export const downloadExcelFromCSV = (csvString: string, fileName: string = 'report.xlsx', title: string, projectname: string): void => {
  const coverSheetData = [
    [title],
    [],
    ['Project:', projectname],
    ['Date:', getDateTimeStrings(new Date().getTime())],
    ['Classification:', 'Confidential'],
    ['Confidentiality Notice:', 'This document is intended only for the recipient(s) and may contain confidential information. Unauthorized use or disclosure is prohibited. If you are not the intended recipient, please notify the sender and delete this document.']
  ];

  // Create cover sheet
  const coverSheet = XLSX.utils.aoa_to_sheet(coverSheetData);

  // Create CSV data sheet
  const csvSheet = XLSX.read(csvString, { type: 'string' }).Sheets.Sheet1;

  // Create a workbook and append both sheets
  const workbook: XLSX.WorkBook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, coverSheet, 'Doc');
  XLSX.utils.book_append_sheet(workbook, csvSheet, title);

  // Write workbook to binary
  const wbout: string = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });

  const s2ab = (s: string): ArrayBuffer => {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  };

  const blob = new Blob([s2ab(wbout)], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  });

  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

function isJSONParsable(str: unknown): boolean {
  if (typeof str !== "string") return false;
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

function isVisible(el: HTMLElement): boolean {
  const style = window.getComputedStyle(el);
  const rect = el.getBoundingClientRect();
  console.log('previous style', style.display, rect, el.id, (
    rect.height > 0 &&
    rect.width > 0
  ) && (
      style.display !== "none" &&
      style.visibility !== "hidden" &&
      style.opacity !== "0"
    ));

  return (
    rect.height > 0 &&
    rect.width > 0
  ) && (
      style.display !== "none" &&
      style.visibility !== "hidden" &&
      style.opacity !== "0"
    );
}

function compareObjects(obj1: any, obj2: any): any {
  if (obj1 === obj2) return {};

  // Case: both are arrays
  if (Array.isArray(obj1) && Array.isArray(obj2)) {
    // One empty, one not → full diff
    if (obj1.length === 0 && obj2.length > 0) {
      return obj2;
    }
    if (obj2.length === 0 && obj1.length > 0) {
      return obj1;
    }

    const maxLength = Math.max(obj1.length, obj2.length);
    const result = [];

    for (let i = 0; i < maxLength; i++) {
      if (i >= obj1.length) {
        result[i] = obj2[i]; // new item
      } else if (i >= obj2.length) {
        result[i] = obj1[i]; // removed item
      } else {
        const diff = compareObjects(obj1[i], obj2[i]);
        if (Object.keys(diff).length > 0) {
          result[i] = diff;
        }
      }
    }

    return result.filter(v => v !== undefined).length > 0 ? result : {};
  }

  // Case: both are objects
  if (
    typeof obj1 === "object" &&
    obj1 !== null &&
    typeof obj2 === "object" &&
    obj2 !== null
  ) {
    const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);
    const diff: any = {};

    for (const key of keys) {
      if (!(key in obj1)) {
        diff[key] = obj2[key];
      } else if (!(key in obj2)) {
        diff[key] = obj1[key];
      } else {
        const valueDiff = compareObjects(obj1[key], obj2[key]);
        if (
          typeof valueDiff === "object" &&
          valueDiff !== null &&
          Object.keys(valueDiff).length === 0
        ) {
          continue;
        }
        if (valueDiff !== undefined) {
          diff[key] = valueDiff;
        }
      }
    }

    return Object.keys(diff).length > 0 ? diff : {};
  }

  // Case: primitives
  return obj1 !== obj2 ? [obj1, obj2] : {};
}

function debounce<T extends (...args: any[]) => void>(
  fn: T,
  delay = 300
) {
  let timer: number;
  return (...args: Parameters<T>) => {
    clearTimeout(timer);
    timer = window.setTimeout(() => fn(...args), delay);
  };
}

async function parseMISExcel(file: File) {
  return file.arrayBuffer().then(data => {
    const workbook = XLSX.read(data, { type: 'array' });
    const metadata: any[] = []
    let compliancesArr: any = {}
    for (let sheetName of workbook.SheetNames) {
      const sheet = workbook.Sheets[sheetName];

      let rows: any[][] = XLSX.utils.sheet_to_json(sheet, {
        header: 1,
        defval: null
      })
      rows = rows.filter((row: any) => {
        let flagNull = true;
        for (let i = 0; i < row.length; i++) {
          if (row[i] != null) {
            flagNull = false
            break;
          }
        }
        return !flagNull;
      });
      let flagNull = true
      if(rows.length <= 0){
        console.log('skipping sheet1', sheetName, rows.length)
        continue;
      }
      for (let i = 0; i < rows[0].length; i++) {
        if (rows[0][i] != null) {
          flagNull = false
          break;
        }
      }
      if (flagNull) {
        rows = rows.slice(1)
      }
      if (rows.length <= 0 || rows[0][0] == null || rows[0][0].indexOf('NAME OF THE FACTORY') < 0) {
        console.log('skipping sheet', sheetName, rows.length, rows[0].length);
        continue;
      }
      
      // console.log('rows', rows);

      // ✅ Metadata extraction
      metadata.push({
        establishmentName: rows[0][1],
        address: rows[1][2],
        dateOfOpening: rows[2][2],
        industry: rows[3][2],
        hrName: rows[4][2],
        coordinator: rows[5][2],
        headCount: Number(rows[6][2])
      });

      console.log('months', rows[7])
      let monthRow = rows[7]
      // ✅ Data starts from row index 10
      let dataRows = []
      dataRows = rows.slice(9);
      console.log('data rows', sheetName, dataRows.length, rows.length);
      compliancesArr[sheetName] = dataRows
        .filter(r => r[1] !== null && r[1] !== "Total")
        .map(row => ({
          labourCode: row[0] ?? "",
          act: row[1],
          documentName: row[2],
          forms: row[3],
          description: row[3],
          status: getMonthlyStatus(row, monthRow),
          periodicity: getMonthlyPeriodicity(row, monthRow),
          remarks: getMonthlyRemarks(row, monthRow)
        }));
    }
    // let compliances: any = {}
    // for(let compliance of compliancesArr){
    //   let id = compliance.no
    //   compliances[id] = compliance
    // }
    return { metadata, compliancesArr };
  });

  function getMonthlyStatus(row: any[], monthsRow: any[]): string {
    let retObj: any = {}
    for (let [indexRow, month] of monthsRow.entries()) {
      if (month != null) {
        if (row[indexRow] === 'ü') {
          retObj[month] = 'Complied'
        } else if (row[indexRow + 1] === 'ü') {
          retObj[month] = 'Delay/Partial Compliance'
        } else if (row[indexRow + 2] === 'ü') {
          retObj[month] = 'Not Complied'
        } else if (row[indexRow + 3] === 'ü') {
          retObj[month] = 'Not Applicable'
        }
      }
    }
    return retObj;
  }
  function getMonthlyPeriodicity(row: any[], monthsRow: any[]): string {
    let retObj: any = {}
    for (let [indexRow, month] of monthsRow.entries()) {
      if (month != null) {
        retObj[month] = row[indexRow + 4]
      }
    }
    return retObj;
  }
  function getMonthlyRemarks(row: any[], monthsRow: any[]): string {
    let retObj: any = {}
    for (let [indexRow, month] of monthsRow.entries()) {
      if (month != null) {
        retObj[month] = row[indexRow + 5]
      }
    }
    return retObj;
  }
}
async function parseMISExcelOld(file: File) {
  return file.arrayBuffer().then(data => {
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];

    const rows: any[][] = XLSX.utils.sheet_to_json(sheet, {
      header: 1,
      defval: null
    });

    // ✅ Metadata extraction
    const metadata = {
      reportMonth: rows[0][0]?.split('OF-')[1] || null,
      establishmentName: rows[1][4],
      address: rows[2][4],
      dateOfOpening: rows[3][4],
      manager: rows[4][4],
      industry: rows[5][4],
      hrName: rows[6][4],
      coordinator: rows[7][4],
      headCount: Number(rows[8][4])
    };

    // ✅ Data starts from row index 10
    const dataRows = rows.slice(10);

    const compliancesArr = dataRows
      .filter(r => r[0] !== null)
      .map(row => ({
        no: row[0],
        act: row[1],
        form: row[2],
        description: row[3],
        status: getStatus(row),
        periodicity: row[9],
        remarks: row[10]
      }));
    let compliances: any = {}
    for (let compliance of compliancesArr) {
      let id = compliance.no
      compliances[id] = compliance
    }
    return { metadata, compliances };
  });

  function getStatus(row: any[]): string {
    if (row[5] === 'ü') return 'Complied';
    if (row[6] === 'ü') return 'Delay/Partial Compliance';
    if (row[7] === 'ü') return 'Not Complied';
    if (row[8] === 'ü') return 'Not Applicable';
    return 'Unknown';
  }
}

const exportFunctions = {
  callApiPresignedDelete, callApiPresignedGet, callApiPresigned, jsonObjectToHtml, clearListeners, isInteger, callApi, validateName, readCookie, timeSince, createDiagonalPattern1, createDiagonalPattern2, createDiagonalPattern3, getRandomColor, convertToCSV, parseCsv, titleCase, alphabeticalSort, percentageString, getCurrentFiscal, getDateTimeStrings, getUsermap, getUserAdhocCheckTime, putUserAdhocCheckTime, getProjectConfigHome, setFeatures, getFeatures, getProjectUsermap, downloadExcelFromCSV, isJSONParsable, isVisible, compareObjects, debounce, parseMISExcel, parseMISExcelOld, convertToCSVStats
};

export default exportFunctions;