import React, { useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import { Box, Button, Typography, ThemeProvider, Modal } from '@mui/material'
import { Link } from 'react-router-dom'
import { FaCloudDownloadAlt, FaCloudUploadAlt, FaFileExcel } from 'react-icons/fa'
import { IoMdReturnRight } from 'react-icons/io'
import { styled, createTheme } from '@mui/material/styles'
import * as XLSX from 'xlsx'
import Papa from 'papaparse'
import { DataGrid, GridToolbarContainer, GridToolbarColumnsButton } from '@mui/x-data-grid'
import { frFR } from '@mui/x-data-grid/locales'
import CustomBar from './CustomBar'
import dayjs from 'dayjs'
import svgSuccess from '../assets/success.svg'

const ImportNiveau = () => {
  const VisuallyHiddenInput = styled('input')({
    clip: 'rect(0 0 0 0)',
    clipPath: 'inset(50%)',
    height: 1,
    overflow: 'hidden',
    position: 'absolute',
    bottom: 0,
    left: 0,
    whiteSpace: 'nowrap',
    width: 1
  })

  const [error, setError] = useState('')
  const [tableData, setTableData] = useState([])
  const [files, setFiles] = useState()
  const [header, setHeader] = useState([])
  let field = []

  for (let index = 0; index < header.length; index++) {
    field.push(header[index].toLowerCase().replace(/\s+/g, '_'))
  }

  const dynamicColumns = header.map((col, index) => ({
    field: col.toLowerCase().replace(/\s+/g, '_'), // Converts the header text to field names (e.g., "Nom" -> "nom")
    headerName: col, // Display the header as is
    width: 150 // Adjust the width as needed
  }))

  const theme = createTheme({
    components: {
      MuiIconButton: {
        styleOverrides: {
          root: {
            color: 'gray' // Toolbar icons color
          }
        }
      },
      MuiButton: {
        styleOverrides: {
          root: {
            color: '#121212' // Button text color
          }
        }
      }
    }
  })

  const paginationModel = { page: 0, pageSize: 5 }

  // Assuming `tableData` is an array where each entry corresponds to a student's data
  const dataRow = tableData.map((etudiant, index) => {
    // Dynamically create an object with fields from the header and data from `etudiant`
    let row = { id: index + 1 } // Unique ID for each row

    field.forEach((fieldName, idx) => {
      if (fieldName === 'date_de_naissance') {
        row[fieldName] = dayjs(etudiant[idx]).format('DD-MM-YYYY') // Format date
      } else {
        row[fieldName] = etudiant[idx] // Assign value to field dynamically
      }
    })

    return row
  })

  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([])
    }
  }

  const exemplaireFileExcel = [
    {
      Nom: 'L1'
    },
    {
      Nom: 'L2'
    },
    {
      Nom: 'L3'
    },
    {
      Nom: 'M1'
    },
    {
      Nom: 'M2'
    }
  ]

  const convertToExcel = () => {
    // convert json to sheet
    const worksheet = XLSX.utils.json_to_sheet(exemplaireFileExcel)

    // Create a new workbook and append the worksheet
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    // Write the workbook to a Blob and create a download link
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
    const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
    const url = URL.createObjectURL(data)

    // Trigger a download
    const link = document.createElement('a')
    link.href = url
    link.download = 'exemplaire_niveau.xlsx'
    link.click()

    // Clean up
    URL.revokeObjectURL(url)
  }

  const handleColumnVisibilityChange = (model) => {
    // Get the currently visible columns
    const visibleColumns = dynamicColumns.filter((column) => model[column.field] !== false)

    // Create a new Excel file with visible columns
    createExcelFile(visibleColumns)
  }

  const createExcelFile = (columns) => {
    // Extract and set the header
    const header = columns.reduce((acc, col) => {
      acc[col.field] = col.headerName || col.field // Use headerName or field as default
      return acc
    }, {})

    // Map the data rows to match the extracted headers
    const worksheetData = dataRow.map((row) => {
      const filteredRow = {}
      columns.forEach((col) => {
        const headerName = header[col.field]
        filteredRow[headerName] = row[col.field]
      })
      return filteredRow
    })

    // Create a worksheet from the data
    const ws = XLSX.utils.json_to_sheet(worksheetData)

    // Create a workbook and add the worksheet to it
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

    // Generate the Excel file as binary data
    const excelFile = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })

    // Create a Blob for the Excel data
    const blob = new Blob([excelFile], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // Create a link element to trigger the download
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'original-file.xlsx' // Original file name or any desired name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url) // Clean up
  }

  /**
   * fonction qui envoye dans le back
   */
  const handleImport = async () => {
    // Code to handle file import (can open a file dialog or call handleFileChange)

    let response = await window.niveaus.importNiveau(files.path)

    console.log(response)
    if (response.success) {
      setOpen(true)
      setTableData([])
    }
  }

  /**
   * hook to open modal
   */
  const [open, setOpen] = useState(false)

  /**
   * function to close modal
   */
  const handleClose = () => setOpen(false)

  /**
   * function to return the view Modal
   *
   * @returns {JSX}
   */
  const modals = () => (
    <Modal
      open={open}
      onClose={handleClose}
      aria-labelledby="modal-title"
      aria-describedby="modal-description"
    >
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 450,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        <Typography
          style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
        >
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Importation a été effectuée avec succès</span>
        </Typography>
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          <Button onClick={handleClose} color="warning" variant="contained">
            OK
          </Button>
        </Box>
      </Box>
    </Modal>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaFileExcel />
              Importation de données
            </h1>
            <Link to={'/addniveau'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      {/* displaying */}
      <Box
        sx={{
          position: 'absolute',
          top: '52%',
          left: '52%',
          transform: 'translate(-50%, -50%)',
          width: '95%',
          borderRadius: '2%',
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        <Box sx={{ mt: 2, display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
          <div style={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
            <Button
              component="label"
              variant="contained"
              color="warning"
              startIcon={<FaCloudUploadAlt />}
            >
              Charger un fichier excel
              <VisuallyHiddenInput type="file" onChange={handleFileChange} accept=".xlsx, .csv" />
            </Button>
            <Button
              component="label"
              variant="contained"
              color="error"
              startIcon={<FaCloudDownloadAlt />}
              onClick={convertToExcel}
            >
              Télécharger le modèle d'import
            </Button>
          </div>
          {error && (
            <Typography color="error" variant="body2">
              {error}
            </Typography>
          )}
          {tableData.length > 0 && (
            <ThemeProvider theme={theme}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'column',
                  width: '100%'
                }}
              >
                <DataGrid
                  rows={dataRow}
                  columns={dynamicColumns}
                  initialState={{ pagination: { paginationModel } }}
                  onColumnVisibilityModelChange={handleColumnVisibilityChange} // Listen for column visibility changes
                  pageSizeOptions={[5, 10]}
                  disableRowSelectionOnClick
                  sx={{
                    width: '100%',
                    height: '100%',
                    minHeight: 400,
                    maxWidth: '100%', // Prevents grid from exceeding the container width
                    '@media (max-width: 600px)': {
                      width: '100%',
                      height: 'auto', // Adjust height for smaller screens
                      fontSize: '0.8rem' // Smaller font size for better readability on small screens
                    },
                    '@media (max-width: 960px)': {
                      fontSize: '1rem' // Adjust font size for medium screens
                    }
                  }}
                  slots={{ toolbar: CustomBar }}
                  slotProps={{ toolbar: { onImport: handleImport } }}
                  localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                />
              </div>
            </ThemeProvider>
          )}
        </Box>
      </Box>
    </div>
  )
}

export default ImportNiveau
