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 jsPDF from 'jspdf'
import html2Canvas from 'html2canvas'
import logoRelerev1 from '../assets/logorelever.png'
import logoRelerev2 from '../assets/logorelever2.png'
import dayjs from 'dayjs'
import getSemestre from './function/GetSemestre'
import { descisionJury, getmentionAfterNotes } from './function/FonctionRelever'

const ReleverNotes = ({ id, anneescolaire, niveau, sessionType = 'ensemble', refs }) => {
  const [etudiant, setEtudiant] = useState([])
  const [matieres, setMatieres] = useState([])
  const [notes, setNotes] = useState([])

  // Fonction pour vérifier si les crédits doivent être affichés
  const shouldShowCredits = () => {
    return niveau !== 'L1' && niveau !== 'L2'
  }

  const handleDownloadPDF = async () => {
    const input = Telever.current

    // Set a high scale for better quality
    const scale = 3

    html2Canvas(input, {
      scale, // Increase resolution
      useCORS: true, // Handle cross-origin images
      allowTaint: true
    }).then((canvas) => {
      const imgData = canvas.toDataURL('image/png')

      // Create a PDF with dimensions matching the captured content
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      })

      const imgWidth = 210 // A4 width in mm
      const pageHeight = 297 // A4 height in mm
      const imgHeight = (canvas.height * imgWidth) / canvas.width

      let position = 0

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST')

      // Handle multi-page case
      while (position + imgHeight >= pageHeight) {
        position -= pageHeight
        pdf.addPage()
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST')
      }

      pdf.save('document.pdf')
    })
  }

  useEffect(() => {
    if (!id) {
      // id doesn't exist, you might want to retry, or do nothing
      // For example, refetch later or show an error
      return
    }
    window.etudiants.getSingle({ id }).then((response) => {
      setEtudiant(response)
    })

    window.mention.getMention().then((response) => {
      setMatieres(response)
    })

    window.notes.noteRelerer({ id, anneescolaire, niveau }).then((response) => {
      setNotes(response)
    })
  }, [id])

  const Telever = useRef()

  useEffect(() => {
    if (refs) {
      handleDownloadPDF()
    }
  }, [refs])

  const [matiereWithSemestre, setMatiereWithSemestre] = useState([])
  const [matiereWithSemestreRepech, setMatiereWithSemestreRepech] = useState([])

  useEffect(() => {
    if (!notes.noteNormal || !notes.semestre || !notes.noteRepech) return // Ensure data exists

    const updatedMatieres = notes.noteNormal.map((matiere) => {
      // Get the semesters based on the student's niveau
      const semesters = getSemestre(matiere.etudiant_niveau)

      // Find the matched semestre based on the conditions
      const matchedSemestre = notes.semestre.find(
        (sem) =>
          sem.matiere_id === matiere.matiere_id &&
          sem.mention_id === matiere.mention_id &&
          (sem.nom === semesters[0] || sem.nom === semesters[1]) // Check if the semester matches
      )

      return {
        ...matiere,
        semestre: matchedSemestre ? matchedSemestre.nom : null // Add 'semestre' or set null if no match
      }
    })

    const updatedMatieresRepech = notes.noteRepech.map((matiere) => {
      // Get the semesters based on the student's niveau
      const semesters = getSemestre(matiere.etudiant_niveau)

      // Find the matched semestre based on the conditions
      const matchedSemestre = notes.semestre.find(
        (sem) =>
          sem.matiere_id === matiere.matiere_id &&
          sem.mention_id === matiere.mention_id &&
          (sem.nom === semesters[0] || sem.nom === semesters[1]) // Check if the semester matches
      )

      // Return the updated matiere with the matched semestre or null if no match
      return {
        ...matiere,
        semestre: matchedSemestre ? matchedSemestre.nom : null // Add 'semestre' or set null if no match
      }
    })

    setMatiereWithSemestre(updatedMatieres)
    setMatiereWithSemestreRepech(updatedMatieresRepech)
  }, [notes])

  function compareMention(mentionID) {
    let statusText

    matieres.map((statu) => {
      if (mentionID == statu.id) {
        statusText = statu.nom
      }
    })

    return statusText ? statusText.charAt(0).toUpperCase() + statusText.slice(1) : statusText
  }

  // data are finaly get and ready for the traitement below

  // Merging the arrays based on matiere_id
  matiereWithSemestre.forEach((item1) => {
    // Find the corresponding item in array2 based on matiere_id
    let matchingItem = matiereWithSemestreRepech.find(
      (item2) => item2.matiere_id === item1.matiere_id
    )

    // If there's a match, add noterepech from array2, otherwise use the note from array1
    item1.noterepech = matchingItem ? matchingItem.note : item1.note
  })

  // step 1 group all by semestre
  const groupedDataBySemestre = matiereWithSemestre.reduce((acc, matiere) => {
    const { semestre } = matiere

    if (!acc[semestre]) {
      acc[semestre] = []
    }

    acc[semestre].push(matiere)

    return acc
  }, {})

  // MODIFICATION: Fonction compareMoyenne mise à jour
  const compareMoyenne = (normal, rattrapage, sessionType) => {
    if (sessionType === 'normale') {
      // Pour session normale: toujours évaluer selon la note normale uniquement
      return Number(normal) >= 10 ? 'Admis' : 'Ajourné'
    } else if (sessionType === 'rattrapage') {
      // Pour session rattrapage: évaluer selon la note de rattrapage
      return Number(rattrapage) >= 10 ? 'Admis' : 'Ajourné'
    } else {
      // Pour session ensemble: prendre la meilleure des deux notes
      const bestNote = Math.max(Number(normal), Number(rattrapage))
      return bestNote >= 10 ? 'Admis' : 'Ajourné'
    }
  }

  const TbodyContent = () => {
    return (
      <>
        {Object.entries(groupedDataBySemestre).map(([semestre, matieres]) => {
          // Group by unite_enseignement inside each semestre
          const groupedByUnite = matieres.reduce((acc, matiere) => {
            if (!acc[matiere.unite_enseignement]) {
              acc[matiere.unite_enseignement] = []
            }
            acc[matiere.unite_enseignement].push(matiere)
            return acc
          }, {})

          return (
            <tbody key={semestre} style={{ border: 'none' }}>
              {Object.entries(groupedByUnite).map(([unite, matieres], uniteIndex) => (
                <>
                  {matieres.map((matiere, matiereIndex) => (
                    <tr key={matiere.id} style={{ border: 'none' }}>
                      {/* Display 'semestre' only for the first row of the first unite_enseignement */}
                      {uniteIndex === 0 && matiereIndex === 0 && (
                        <td
                          rowSpan={
                            Object.values(groupedByUnite).flat().length +
                            Object.values(groupedByUnite).flat().length
                          }
                          style={{
                            fontWeight: 'bold',
                            textAlign: 'center',
                            paddingTop: '8px',
                            borderRight: 'solid 1px black',
                            borderBottom: 'solid 1px black',
                            background: '#bdbcbc',
                            borderLeft: 'solid 1px black'
                          }}
                        >
                          {semestre}
                        </td>
                      )}

                      {/* Display 'unite_enseignement' only for the first row of each group */}
                      {matiereIndex === 0 && (
                        <td
                          rowSpan={matieres.length}
                          style={{
                            fontWeight: 'bold',
                            textAlign: 'center',
                            borderRight: 'solid 1px black',
                            borderTop: 'solid 1px black'
                          }}
                        >
                          {unite}
                        </td>
                      )}

                      {/* Matiere Data */}
                      <td style={{ borderRight: 'solid 1px black', borderTop: 'solid 1px black' }}>
                        {matiere.nom}
                      </td>
                      
                      {/* Affichage conditionnel des colonnes selon le type de session */}
                      {sessionType !== 'rattrapage' && (
                        <>
                          <td style={{ borderRight: 'solid 1px black', borderTop: 'solid 1px black' }}>
                            {matiere.credit}
                          </td>
                          <td style={{ borderRight: 'solid 1px black', borderTop: 'solid 1px black' }}>
                            {matiere.note}
                          </td>
                        </>
                      )}
                      
                      {sessionType !== 'normale' && (
                        <>
                          <td style={{ borderRight: 'solid 1px black', borderTop: 'solid 1px black' }}>
                            {matiere.credit}
                          </td>
                          <td style={{ borderRight: 'solid 1px black', borderTop: 'solid 1px black' }}>
                            {matiere.noterepech}
                          </td>
                        </>
                      )}

                      {/* Display the comparison value only once */}
                      {matiereIndex === 0 && (
                        <td
                          rowSpan={matieres.length}
                          style={{
                            fontWeight: 'bold',
                            textAlign: 'center',
                            borderRight: 'solid 1px black',
                            borderTop: 'solid 1px black'
                          }}
                        >
                          {compareMoyenne(
                            (
                              matieres.reduce((total, matiere) => total + matiere.note, 0) /
                              matieres.length
                            ).toFixed(2),
                            (
                              matieres.reduce((total, matiere) => total + matiere.noterepech, 0) /
                              matieres.length
                            ).toFixed(2),
                            sessionType // MODIFICATION: Passer le sessionType
                          )}
                        </td>
                      )}
                    </tr>
                  ))}

                  {/* Add Total Row for 'unite_enseignement' */}
                  <tr
                    style={{ background: '#bdbcbc', border: 'none', borderLeft: 'solid 1px black' }}
                  >
                    <td
                      colSpan={2}
                      style={{
                        textAlign: 'right',
                        fontWeight: 'bold',
                        borderRight: 'solid 1px black',
                        borderBottom: 'none',
                        borderLeft: 'solid 1px black',
                        borderTop: 'solid 1px black'
                      }}
                    >
                      Total de Credit et Moyenne des Notes
                    </td>
                    
                    {sessionType !== 'rattrapage' && (
                      <>
                        <td
                          style={{
                            textAlign: 'center',
                            fontWeight: 'bold',
                            borderRight: 'solid 1px black',
                            borderTop: 'solid 1px black'
                          }}
                        >
                          {matieres.reduce((total, matiere) => total + matiere.credit, 0)}
                        </td>
                        <td
                          style={{
                            textAlign: 'center',
                            fontWeight: 'bold',
                            borderRight: 'solid 1px black',
                            borderTop: 'solid 1px black'
                          }}
                          className="moyenneNotes"
                        >
                          {(
                            matieres.reduce((total, matiere) => total + matiere.note, 0) /
                            matieres.length
                          ).toFixed(2)}
                        </td>
                      </>
                    )}
                    
                    {sessionType !== 'normale' && (
                      <>
                        <td
                          style={{
                            textAlign: 'center',
                            fontWeight: 'bold',
                            borderTop: 'solid 1px black',
                            borderRight: 'solid 1px black'
                          }}
                        >
                          {matieres.reduce((total, matiere) => total + matiere.credit, 0)}
                        </td>
                        <td
                          style={{
                            textAlign: 'center',
                            fontWeight: 'bold',
                            borderRight: 'solid 1px black',
                            borderTop: 'solid 1px black'
                          }}
                          className="moyenneNotesRattrapage"
                        >
                          {(
                            matieres.reduce((total, matiere) => total + matiere.noterepech, 0) /
                            matieres.length
                          ).toFixed(2)}
                        </td>
                      </>
                    )}
                    
                    <td
                      style={{
                        textAlign: 'center',
                        fontWeight: 'bold',
                        borderRight: 'solid 1px black',
                        borderTop: 'solid 1px black'
                      }}
                    ></td>
                  </tr>
                </>
              ))}
            </tbody>
          )
        })}
      </>
    )
  }

  // MODIFICATION: Fonction totalNotes mise à jour pour tenir compte du sessionType
  const totalNotes = () => {
    let totalNotes = document.querySelectorAll('.moyenneNotes')
    let totalNotesRepech = document.querySelectorAll('.moyenneNotesRattrapage')

    let TotalNoteNumber = 0
    let TotalNoteNumberRepech = 0

    totalNotes.forEach((notes) => {
      TotalNoteNumber += Number(notes.textContent) / totalNotes.length
    })

    totalNotesRepech.forEach((notes) => {
      TotalNoteNumberRepech += Number(notes.textContent) / totalNotesRepech.length
    })

    // Retourner la note selon le type de session
    if (sessionType === 'normale') {
      return TotalNoteNumber
    } else if (sessionType === 'rattrapage') {
      return TotalNoteNumberRepech
    } else {
      // Pour 'ensemble', prendre la meilleure note
      return Math.max(TotalNoteNumber, TotalNoteNumberRepech)
    }
  }

  const [note, setNote] = useState(0)

  useEffect(() => {
    setNote(totalNotes())
  }, [TbodyContent, sessionType])

  return (
    <div className={classe.mainHome}>
      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              height: 'auto',
              minHeight: 500,
              display: 'flex',
              padding: '1%',
              width: '70%',
              marginTop: '2%',
              justifyContent: 'center'
            }}
            ref={Telever}
          >
            <div style={{ width: '80%' }}>
              <div
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
              >
                <img src={logoRelerev1} alt="image en tete" width={70} />
                <img src={logoRelerev2} alt="image en tete" width={70} />
              </div>
              <hr style={{ margin: 0, border: 'solid 1px black' }} />
              <h4 style={{ textTransform: 'uppercase', textAlign: 'center', marginBottom: 0 }}>
                Releve de notes
              </h4>
              <hr style={{ margin: 0, border: 'solid 1px black' }} />
              {/* block info */}
              <div style={{ marginTop: '2px', display: 'flex' }}>
                {/* gauche */}
                <div style={{ display: 'flex', width: '60%' }}>
                  {/* gauche gauche */}
                  <div style={{ width: '40%' }}>
                    <span>
                      <b>Nom</b>
                    </span>
                    <br />
                    <span>
                      <b>Prénom</b>
                    </span>
                    <br />
                    <span>
                      <b>Date de naissance</b>
                    </span>
                    <br />
                    <span>
                      <b>Codage</b>
                    </span>
                  </div>
                  {/* gauche droite */}
                  <div style={{ width: '60%' }}>
                    <span>: {etudiant.nom}</span>
                    <br />
                    <span>: {etudiant.prenom}</span>
                    <br />
                    <span>: {dayjs(etudiant.date_de_naissances).format('DD/MM/YYYY')}</span>
                    <br />
                    <span>: {etudiant.num_inscription}</span>
                  </div>
                </div>
                {/* droite */}
                <div style={{ display: 'flex', width: '40%' }}>
                  {/* droite gauche */}
                  <div style={{ width: '30%' }}>
                    <span>
                      <b>Annee U</b>
                    </span>
                    <br />
                    <span>
                      <b>Niveau</b>
                    </span>
                    <br />
                    <span>
                      <b>Parcours</b>
                    </span>
                  </div>
                  {/* droite droite */}
                  <div style={{ width: '70%' }}>
                    <span>: {etudiant.annee_scolaire}</span>
                    <br />
                    <span>: {etudiant.niveau}</span>
                    <br />
                    <span>: {compareMention(etudiant.mention_id)}</span>
                  </div>
                </div>
              </div>

              {/* table */}
              <table style={{ marginTop: '5px', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ borderTop: 'solid 1px black', textAlign: 'center' }}>
                    <th colSpan={3}></th>
                    <th
                      colSpan={sessionType === 'ensemble' ? 4 : 2}
                      style={{
                        background: '#bdbcbc',
                        borderLeft: 'solid 1px black',
                        borderRight: 'solid 1px black'
                      }}
                    >
                      Session
                    </th>
                    <th></th>
                  </tr>
                  <tr style={{ borderTop: 'solid 1px black', textAlign: 'center' }}>
                    <th style={{ borderLeft: 'solid 1px black' }}></th>
                    <th style={{ borderLeft: 'solid 1px black' }}></th>
                    <th style={{ borderLeft: 'solid 1px black' }}></th>
                    
                    {sessionType !== 'rattrapage' && (
                      <th
                        colSpan={shouldShowCredits() ? 2 : 1}
                        style={{ background: '#bdbcbc', borderLeft: 'solid 1px black' }}
                      >
                        Normale
                      </th>
                    )}
                    
                    {sessionType !== 'normale' && (
                      <th
                        colSpan={shouldShowCredits() ? 2 : 1}
                        style={{ background: '#bdbcbc', borderLeft: 'solid 1px black' }}
                      >
                        Rattrapage
                      </th>
                    )}
                    
                    <th
                      style={{ borderLeft: 'solid 1px black', borderRight: 'solid 1px black' }}
                    ></th>
                  </tr>
                  <tr
                    style={{
                      borderTop: 'solid 1px black',
                      background: '#bdbcbc',
                      textAlign: 'center'
                    }}
                  >
                    <th style={{ borderLeft: 'solid 1px black', borderBottom: 'solid 1px black' }}>
                      semestre
                    </th>
                    <th style={{ borderLeft: 'solid 1px black' }}>UE</th>
                    <th style={{ borderLeft: 'solid 1px black' }}>EC</th>
                    
                    {sessionType !== 'rattrapage' && (
                      <>
                        <th style={{ borderLeft: 'solid 1px black', padding: '0 5px' }}>crédit</th>
                        <th style={{ borderLeft: 'solid 1px black', padding: '0 5px' }}>Notes</th>
                      </>
                    )}
                    
                    {sessionType !== 'normale' && (
                      <>
                        <th style={{ borderLeft: 'solid 1px black', padding: '0 5px' }}>crédit</th>
                        <th style={{ borderLeft: 'solid 1px black', padding: '0 5px' }}>Notes</th>
                      </>
                    )}
                    
                    <th style={{ borderLeft: 'solid 1px black', borderRight: 'solid 1px black' }}>
                      Observation
                    </th>
                  </tr>
                </thead>
                <TbodyContent />
                <tbody style={{ fontWeight: 'bold' }}>
                  <tr style={{ border: 'solid 1px black' }}>
                    <td
                      colSpan={2}
                      style={{
                        borderRight: 'solid 1px black',
                        textAlign: 'left',
                        paddingLeft: '2%'
                      }}
                    >
                      Moyenne
                    </td>
                    <td style={{ borderRight: 'solid 1px black' }}>{note.toFixed(2)}</td>
                    <td style={{ borderRight: 'solid 1px black' }}>/20</td>
                    <td colSpan={sessionType === 'ensemble' ? 3 : 2}></td>
                  </tr>
                  <tr style={{ border: 'solid 1px black' }}>
                    <td
                      colSpan={3}
                      style={{
                        borderRight: 'solid 1px black',
                        textAlign: 'left',
                        paddingLeft: '2%'
                      }}
                    >
                      Mention:{' '}
                      <span style={{ marginLeft: '3%' }}>{getmentionAfterNotes(note)}</span>
                    </td>
                    <td colSpan={sessionType === 'ensemble' ? 4 : 3} style={{ textAlign: 'left', paddingLeft: '1%' }}>
                      Décision du Jury:{' '}
                    </td>
                  </tr>
                </tbody>
              </table>
              <div style={{ textAlign: 'right', marginRight: '20%' }}>
                <p>
                  <b>Toamasine le</b>
                </p>
                {/* texte hidden for place in signature */}
                <p style={{ visibility: 'hidden' }}>
                  Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis delectus
                  perspiciatis nisi aliquid eos adipisci cumque amet ratione error voluptatum.
                  Expedita velit enim nulla nam? Vitae fuga enim et temporibus. Lorem ipsum dolor
                  sit amet, consectetur adipisicing elit. Mollitia, assumenda?
                </p>
              </div>
            </div>
          </Paper>
        </div>
      </div>
    </div>
  )
}

export default ReleverNotes