import * as ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'
import imageToBase64 from 'image-to-base64/browser'

const obtenerExtensionImagen = (path) => {
  const ext = path.split('.').pop();
  return ext.toLowerCase();
}

const excelCondensado = async (
  columnas,
  datos,
  totalEventos,
  eventos,
  nombre = "archivo-excel",
  titulo = "archivo-excel",
  subtitulo = "",
  path = null
) => {

  try {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet(titulo.replace(/[^a-zA-Z ]/g, ""), {
      views: [
        { state: "frozen", xSplit: 6 }, // Fijar columna
        { state: "frozen", ySplit: 7 }, // Fijar renglon
      ],
    })

    if( path !== null && typeof path === 'string' ) {
      const img64 = await imageToBase64(path)
      const idImagen = workbook.addImage({
        base64: img64,
        extension: obtenerExtensionImagen(path), 
      })

      worksheet.addImage( idImagen, {
        tl: { col: 1.5, row: 0.5 },
        br: { col: 2.5, row: 3.5 },
        editAs: 'oneCell'
      })
    }

    const cols = columnas
    const data = datos
    const header = cols.map(c => (c.title));

    worksheet.columns = cols

    const styleTitle = {
      font: {
        bold: true,
        size: 18,
      },
      aligment: {
        horizontal: 'center',
        vertical: 'center',
        wrapText: true
      },
    }

    const styleSubTitle = {
      font: {
        bold: false,
        size: 15,
      },
      aligment: {
        horizontal: 'center',
        vertical: 'center',
        wrapText: true
      },
    }

    const totalTitle = {
      font: {
        bold: true,
        size: 14,
      },
    }
    const totalSubTitle = {
      font: {
        bold: false,
        size: 14,
      },
    }

    // Cobinar celdas
    worksheet.mergeCells('A1:F4')
    worksheet.mergeCells('A5:F5')
    worksheet.mergeCells('A6:F6')


    worksheet.addRow(header)
    for( let i = 0; i < data?.length; i++ ) {
      let row = data[i];
      worksheet.addRow(row);
    }

    worksheet.columns.forEach(( column, index ) => {
      let dataMax = 0;


      column.eachCell({ includeEmpty: true }, (cell, index) => {

        if((index % 2) === 0  && index > 6){
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "E7E7E7" },
          };
        }

        if(column.key === "participacion") {
          cell.numFmt = '0.00%';
        }

        if( 
          Number.isInteger(cell?.value) && 
          cell?.value === 1 && 
          column?.key !== "participacion" &&
          column?.key !== "participo"
        ) {
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "8EF0C3" },
          };
        }

        if(!cell?.value || Number.isInteger(cell?.value)) {
          return true;
        }      
        const tipoRed = `${cell?.value}`.split("-")?.length === 4 ? `${cell?.value}`.split("-")[0] : "";

        if (tipoRed.trim() === "INS") {
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "C6ADF3" },
          };
        } else if (tipoRed.trim() === "TW") {
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "ADF3F0" },
          };
        } else if (tipoRed.trim() === "FB") {
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "ADCDF3" },
          };
        }  else if ( `${cell?.value}`.trim() === "Participacion" ) {
          cell.fill = {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "F7DB15" },
          };
        }

        let columnLength = cell.value?.length;
        if( columnLength > dataMax ) {
          dataMax = columnLength;
        }
      })
      column.width = dataMax < 10 ? 10 : dataMax;
    })

    const colA = worksheet.getColumn("A")
    colA.width = 15
    const colB = worksheet.getColumn("B")
    colB.width = 15
    const colC = worksheet.getColumn("C")
    colC.width = 15

    worksheet.getCell('H2').value = "Eventos Facebook"; 
    worksheet.getCell('I2').value = "Eventos Instagram"; 
    worksheet.getCell('J2').value = "Eventos Twitter"; 
    worksheet.getCell('L2').value = "Total de eventos"; 

    worksheet.getCell('H3').value = totalEventos?.Facebook; 
    worksheet.getCell('I3').value = totalEventos?.Instagram; 
    worksheet.getCell('J3').value = totalEventos?.Twitter; 
    worksheet.getCell('L3').value = eventos; 

    worksheet.getCell('H2').style = totalTitle;
    worksheet.getCell('I2').style = totalTitle;
    worksheet.getCell('J2').style = totalTitle;
    worksheet.getCell('L2').style = totalTitle;

    worksheet.getCell('H3').style = totalSubTitle;
    worksheet.getCell('I3').style = totalSubTitle;
    worksheet.getCell('J3').style = totalSubTitle;
    worksheet.getCell('L3').style = totalSubTitle;

    worksheet.getCell('A5').value = titulo;
    worksheet.getCell('A5').style = styleTitle
    worksheet.getCell('A5').alignment = { vertical: 'middle', horizontal: 'left' }

    worksheet.getCell('A6').value = subtitulo;
    worksheet.getCell('A6').style = styleSubTitle
    worksheet.getCell('A6').alignment = { vertical: 'middle', horizontal: 'left' }

    workbook.xlsx.writeBuffer().then(( data ) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(blob, `${nombre}.xlsx`)
    })

  } catch (error) {
    console.log(error)
  }

}

export default excelCondensado