const handleFileChange = (event) => {
  const file = event.target.files[0]
  setFiles(event.target.files[0])
  if (!file) {
    setError('No file selected')
    return
  }

  const fileExtension = file.name.split('.').pop().toLowerCase()

  if (fileExtension === 'xlsx') {
    const reader = new FileReader()
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })

      // Extract data from all sheets and combine
      const allData = []
      workbook.SheetNames.forEach((sheetName) => {
        const worksheet = workbook.Sheets[sheetName]
        const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        setHeader(rows[0]) // keep the header
        allData.push(...rows.slice(1)) // Skip header row for each sheet
      })
      setTableData(allData)
    }
    reader.readAsArrayBuffer(file)
  } else if (fileExtension === 'csv') {
    const reader = new FileReader()
    reader.onload = (e) => {
      Papa.parse(e.target.result, {
        complete: (results) => {
          setHeader(results.data[0]) // keep the header
          setTableData(results.data.slice(1)) // Skip header row
        },
        header: false
      })
    }
    reader.readAsText(file)
  } else {
    setError('Unsupported file format. Please upload .xlsx or .csv file.')
    setTableData([])
  }
}
