import React from 'react'
import * as xlsx from 'xlsx'
import styled from 'styled-components'
import { Button } from '../Button/Button' 
import excelIcon from './excel-icon.svg'
import csvIcon from './csv-icon.svg'

interface IDownloadData {
   [k: number | string | symbol]: boolean | number | string;
}

export type DownloadDataProps = {
  css?:string;
  /**
   * array of data objects, e.g. [{a:1,b:2},{a:3,b:4}]
   */
  data: IDownloadData[]
    /**
   * automatically adds extension when it is not supplied
   */
  filename?: string;
  filetype?: 'xlsx'|'csv' 
};

export const DownloadData = ({ data,filename='test',filetype,css }: DownloadDataProps):JSX.Element => {
  filename = filename.split('.')[0]
  
  const handleDownload = () => {
    if(filetype === 'csv') 
      downloadCsv(data)
    
    else if(filetype === 'xlsx') 
      downloadXlsx(data)
  }

  const downloadXlsx = (array:IDownloadData[]) => {
    const workbook = xlsx.utils.book_new()
    const worksheet = xlsx.utils.json_to_sheet(array)
    xlsx.utils.book_append_sheet(workbook,worksheet,filename)
    xlsx.writeFile(workbook,`${filename}.xlsx`)
  }

  const downloadCsv = (array: IDownloadData[]) => {
    let csv = ''
    const header = Object.keys(array[0]).join(',')
    const values = array.map((o:{[key:string]:unknown}) => Object.values(o).join(',')).join('\n')
    csv += header + '\n' + values
    
    const blob = new Blob([csv],{ type: 'text/csv' })
  
    const a = document.createElement('a')
    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    const clickEvt = new MouseEvent('click',{
      view: window,
      bubbles: true,
      cancelable: true,
    })
    a.dispatchEvent(clickEvt)
    a.remove()
  }

  return (
    <Container css={css}>
      <Button 
        css="button {background-color: #1d6f42;}"
        onClick={handleDownload}
        icon={<Img src={filetype ==='xlsx'?excelIcon:csvIcon}/>}>
          Download
      </Button>
    </Container>
  )
}

const Container = styled.div<{css?:string}>`
  ${(p) => p.css}
`

const Img = styled.img`
  height:20px;
`