import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import Paper from '@mui/material/Paper'
import entete from '../assets/enteterelever.png'
import jsPDF from 'jspdf'
import html2Canvas from 'html2canvas'

const TesteDatagrid = ({ id, niveau, annee_scolaire, nomPrenom, inscription, refs }) => {
  const [print, setPrint] = useState(refs)
  const paperRef = useRef()

  const [teste, setTeste] = useState([])
  useEffect(() => {
    window.notes.noteMatiere({ id, niveau, annee_scolaire }).then((response) => {
      setTeste(response)
    })
  }, [id, niveau, annee_scolaire])

  console.log(teste)

  useEffect(() => {
    if (refs) {
      let certificat = paperRef.current
      html2Canvas(certificat, { scale: 3 }).then((canvas) => {
        const URLimg = canvas.toDataURL()
        const doc = new jsPDF('portrait', 'mm', 'a4')
        const width = doc.internal.pageSize.getWidth()
        const height = doc.internal.pageSize.getHeight()
        doc.addImage(URLimg, 'PNG', 0, 0, width, height)
        doc.save(`releve_${nomPrenom}.pdf`)
      })
    }
  }, [refs])

  // Step 1: Group by semestre
  const groupedBySemestre = teste.reduce((acc, item) => {
    const { semestre, unite_enseignement } = item

    // Ensure a group exists for this `semestre`
    if (!acc[semestre]) {
      acc[semestre] = {}
    }

    // Step 2: Further group by unite_enseignement
    if (!acc[semestre][unite_enseignement]) {
      acc[semestre][unite_enseignement] = []
    }

    acc[semestre][unite_enseignement].push(item) // Add the item to the appropriate group
    return acc
  }, {})
  console.log(groupedBySemestre)

  // Initialize semestre1 and semestre2
  let semestre1 = {}
  let semestre2 = {}

  // Separate groupedBySemestre into semestre1 and semestre2 dynamically
  Object.keys(groupedBySemestre).forEach((semestre) => {
    // Check if the semester is odd or even
    if (parseInt(semestre.replace('S', '')) % 2 !== 0) {
      // Odd semesters (S1, S3, S5, ...)
      semestre1[semestre] = groupedBySemestre[semestre]
    } else {
      // Even semesters (S2, S4, S6, ...)
      semestre2[semestre] = groupedBySemestre[semestre]
    }
  })

  // Function to count the total elements in the groupedData
  function countTotalElements(data) {
    let totalCount = 0

    // Iterate through each key in the object
    Object.keys(data).forEach((key) => {
      // Add the length of the array at the current key to totalCount
      totalCount += data[key].length
    })

    return totalCount
  }

  function crontCredit() {
    let total = 0
    let credit = document.querySelectorAll('.classCredit')
    for (let index = 0; index < credit.length; index++) {
      total += Number(credit[index].textContent)
    }
    return total
  }

  function countMoyenneGeneral() {
    let total = 0
    let moyenne = document.querySelectorAll('.classMoyenne')
    for (let index = 0; index < moyenne.length; index++) {
      total += Number(moyenne[index].textContent)
    }

    return (total / moyenne.length).toFixed(2)
  }

  // Combine both semesters into one object to handle them together
  const combinedSemesters = { ...semestre1, ...semestre2 }

  // Function to generate the rows
  const generateTableRows = (semesters) => {
    const rows = []

    // Iterate over each semester's keys (S1, S2, etc.)
    Object.keys(semesters).forEach((semestreKey) => {
      const units = semesters[semestreKey]

      // Iterate over each unite_enseignement
      Object.keys(units).forEach((unitKey, idx) => {
        const unitArray = units[unitKey]
        const isFirstRow = idx === 0 // Check if it's the first row for this unit

        unitArray.forEach((item, itemIdx) => {
          rows.push(
            <tr key={`${semestreKey}-${unitKey}-${item.id}`}>
              {isFirstRow && itemIdx === 0 ? (
                <td
                  rowSpan={countTotalElements(units)}
                  key={`${semestreKey}-semestre`}
                  style={{ borderBottom: 'solid 1px black', borderRight: 'solid 1px black' }}
                >
                  <b>{semestreKey}</b>
                </td>
              ) : null}

              {itemIdx === 0 ? (
                <td
                  rowSpan={unitArray.length}
                  key={`${unitKey}-unit`}
                  style={{
                    borderBottom: 'solid 1px black',
                    margin: 0,
                    padding: 0,
                    fontSize: 12,
                    borderRight: 'solid 1px black'
                  }}
                >
                  <b>{unitKey}</b>
                </td>
              ) : null}

              <td
                style={{
                  borderBottom: 'solid 1px black',
                  margin: 0,
                  padding: 0,
                  fontSize: 12,
                  borderRight: 'solid 1px black'
                }}
              >
                {item.nom}
              </td>
              <td
                style={{
                  borderBottom: 'solid 1px black',
                  margin: 0,
                  padding: 0,
                  fontSize: 12,
                  borderRight: 'solid 1px black'
                }}
              >
                {' '}
                <span className="classCredit">{item.credit}</span>
              </td>
              <td
                style={{
                  borderBottom: 'solid 1px black',
                  margin: 0,
                  padding: 0,
                  fontSize: 12,
                  borderRight: 'solid 1px black'
                }}
              >
                {item.note}
              </td>

              {/* Ensure this <td> renders only once for the unitArray */}
              {itemIdx === 0 ? (
                <td
                  rowSpan={unitArray.length}
                  style={{ borderBottom: 'solid 1px black', margin: 0, padding: 0, fontSize: 12 }}
                >
                  <span className="classMoyenne">
                    {(
                      unitArray.reduce((sum, item) => sum + item.credit * item.note, 0) /
                      unitArray.reduce((sum, item) => sum + item.credit, 0)
                    ).toFixed(2)}
                  </span>
                </td>
              ) : null}
            </tr>
          )
        })
      })
    })
    return rows
  }

  return (
    <div className={classe.mainHome}>
      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              // width: "100%",
              height: 'auto', // Auto height to make the grid responsive
              minHeight: 500, // Ensures a minimum height
              display: 'flex',
              padding: '1%'
            }}
            ref={paperRef}
          >
            <div>
              <img src={entete} alt="image en tete" style={{ border: 'solid 1px gray' }} />
              <div
                style={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexDirection: 'column',
                    fontWeight: 'bold',
                    textTransform: 'uppercase',
                    border: 'solid 1px gray',
                    margin: '1%',
                    width: '70%',
                    fontSize: '13px'
                  }}
                >
                  <span>ECOLE SUPERIEURE POLYTECHNIQUE</span>
                  <span>REPOBLIKAN’I MADAGASIKARA</span>
                  <span>Fitiavana-Tanindrazana-Fandrosoana</span>
                  <span>*********************</span>
                  <h2>RELEVÉE DE NOTE</h2>
                </div>
              </div>
              <div style={{ fontSize: '13px', margin: '1%' }}>
                <span>Nom & Prénoms: </span>
                <span>{nomPrenom}</span>
                <br />
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span>Année Univesitaire: </span>
                  <span>{annee_scolaire}</span>
                  <span>Niveau: </span>
                  <span>{niveau}</span>
                  <span>inscription: </span>
                  <span>{inscription}</span>
                </div>
              </div>
              <table
                style={{
                  border: 'solid 1px black',
                  margin: 0,
                  padding: 0,
                  fontSize: 12,
                  width: '100%'
                }}
              >
                <thead>
                  <tr>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        borderRight: 'solid 1px black'
                      }}
                    ></th>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        borderRight: 'solid 1px black',
                        textAlign: 'center'
                      }}
                    >
                      Unités <br /> d’Enseignement <br /> (UE)
                    </th>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        borderRight: 'solid 1px black',
                        textAlign: 'center'
                      }}
                    >
                      Eléments constitutifs
                    </th>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        borderRight: 'solid 1px black',
                        textAlign: 'center'
                      }}
                    >
                      Crédits
                    </th>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        borderRight: 'solid 1px black',
                        textAlign: 'center'
                      }}
                    >
                      Note
                    </th>
                    <th
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 12,
                        textAlign: 'center',
                        width: '250px'
                      }}
                    >
                      Moyenne
                    </th>
                  </tr>
                </thead>
                <tbody style={{ margin: 0, padding: 0 }}>
                  {generateTableRows(combinedSemesters)}

                  <tr>
                    <td
                      colSpan={3}
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 13,
                        borderRight: 'solid 1px black',
                        textAlign: 'right',
                        paddingRight: '3px'
                      }}
                    >
                      {' '}
                      <b>Total crédit:</b>
                    </td>
                    <td
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 13,
                        textAlignLast: 'left',
                        paddingLeft: '20px',
                        borderRight: 'solid 1px black'
                      }}
                    >
                      <b>{crontCredit()}</b>
                    </td>
                    <td
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 13,
                        borderRight: 'solid 1px black'
                      }}
                    ></td>
                    <td
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 13
                      }}
                    ></td>
                  </tr>
                  <tr>
                    <td
                      colSpan={5}
                      style={{
                        margin: 0,
                        padding: 0,
                        fontSize: 13,
                        borderRight: 'solid 1px black',
                        textAlign: 'right',
                        paddingRight: '3px'
                      }}
                    >
                      <b>Moyenne générale :</b>
                    </td>
                    <td>
                      <b>{countMoyenneGeneral()}</b>
                    </td>
                  </tr>
                  <tr>
                    <td
                      colSpan={5}
                      style={{
                        borderBottom: 'solid 1px black',
                        margin: 0,
                        padding: 0,
                        fontSize: 13,
                        borderRight: 'solid 1px black',
                        textAlign: 'right',
                        paddingRight: '3px'
                      }}
                    >
                      <b>Observation :</b>
                    </td>
                    <td>
                      <input
                        type="text"
                        style={{
                          border: 'none',
                          outline: 'none',
                          width: '100%',
                          textAlign: 'center'
                        }}
                      />
                    </td>
                  </tr>
                </tbody>
              </table>
              <div style={{ textAlign: 'center', marginTop: '1%' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                  <span>Décision de jury :</span>
                  <input type="text" style={{ border: 'none', width: '300px', outline: 'none' }} />
                </div>
                <p>Le Directeur </p>
              </div>
              <p style={{ textAlign: 'right', marginTop: '5%' }}>RATSIMBAZAFY Christian Pierre</p>
            </div>
          </Paper>
        </div>
      </div>
    </div>
  )
}

export default TesteDatagrid
