import React, { useEffect, useRef, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import { FaBook, FaDownload } from 'react-icons/fa'
import { IoMdReturnRight } from 'react-icons/io'
import { Box, Button, Typography, ThemeProvider, Modal } from '@mui/material'
import Paper from '@mui/material/Paper'
import html2cancas from 'html2canvas'
import jsPDF from 'jspdf'
import autoTable from 'jspdf-autotable'

const ModalExportFichr = () => {
  const [fiche, setFiche] = useState([])
  const [mentions, setMentions] = useState([])
  const PaperRef = useRef()

  let { matiere_id } = useParams()
  let { nom } = useParams()

  useEffect(() => {
    if (matiere_id !== null && matiere_id !== undefined) {
      window.notesysteme.extractFiches({ matiere_id }).then((response) => {
        setFiche(response)
      })
    }
    window.mention.getMention().then((response) => {
      setMentions(response)
    })
  }, [matiere_id])

  // Sort by NomPrenom alphabetically
  const sortedStudents = fiche.sort((a, b) => a.nom.localeCompare(b.nom))

  function compareMention(id) {
    let mentionText
    mentions.map((ment) => {
      if (id == ment.id) {
        mentionText = ment.nom
      }
    })

    return mentionText
  }

  // const download = () => {
  //   const generatePDF = async () => {
  //     try {
  //       await new Promise((resolve) => setTimeout(resolve, 500));

  //       const canvas = await html2cancas(PaperRef.current, {
  //         scale: 2,
  //         useCORS: true,
  //         logging: false,
  //         backgroundColor: "#ffffff",
  //         imageTimeout: 0, // ⬅️ Prevent timeout errors
  //       });

  //       const imgData = canvas.toDataURL("image/jpeg", 0.8); // Use JPEG for smaller size
  //       const pdf = new jsPDF({
  //         orientation: "portrait",
  //         unit: "mm",
  //         format: "a4",
  //         compress: true,
  //       });

  //       let imgWidth = 210;
  //       let imgHeight = (canvas.height * imgWidth) / canvas.width;
  //       let yPosition = 0;

  //       // If image height is greater than A4 page height, add multiple pages
  //       while (yPosition < imgHeight) {
  //         pdf.addImage(imgData, "JPEG", 0, yPosition * -1, imgWidth, imgHeight);
  //         if (yPosition + 297 < imgHeight) pdf.addPage(); // A4 height = 297mm
  //         yPosition += 297;
  //       }

  //       pdf.save("document.pdf");

  //     } catch (error) {
  //       console.error("Error generating PDF:", error);
  //     }
  //   };
  //   generatePDF();
  // }

  const download = () => {
    const generatePDF = () => {
      try {
        const pdf = new jsPDF({
          orientation: 'portrait',
          unit: 'mm',
          format: 'a4'
        })

        // Select the table
        autoTable(pdf, {
          html: '#myTable', // ID de la table
          startY: 20,
          theme: 'grid',
          headStyles: {
            fillColor: 'gray',
            halign: 'center',
            fontStyle: 'bold',
            textColor: 'black'
          }, // Supprimer la couleur et centrer
          margin: { top: 10 },
          styles: { fontSize: 8, cellPadding: 2, halign: 'center' }, // Centrer le texte des cellules
          didDrawPage: (data) => {
            pdf.text('', 14, 10)
          }
        })

        pdf.save('document.pdf')
      } catch (error) {
        console.error('Error generating PDF:', error)
      }
    }
    generatePDF()
  }

  return (
    <div className={classe.mainHome}>
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaBook />
              Matiere
            </h1>
            <div style={{ display: 'flex', gap: '10px' }}>
              <Link to={'#'} onClick={download}>
                <Button color="warning" variant="contained">
                  <FaDownload style={{ fontSize: '20px' }} />
                </Button>
              </Link>
              <Link to={'/matiere'}>
                <Button color="warning" variant="contained">
                  <IoMdReturnRight style={{ fontSize: '20px' }} />
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <Paper
          sx={{
            // alignItems: "center",
            // justifyContent: "center",
            width: '100%'
          }}
          ref={PaperRef}
        >
          <div
            style={{
              padding: '10px',
              textAlign: 'center',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <table style={{ border: 'solid 1px gray', fontSize: '20px' }} id="myTable">
              <thead>
                <tr style={{ textAlign: 'center', borderBottom: 'solid 1px gray' }}>
                  <th colSpan={4}> {nom} </th>
                </tr>
                <tr style={{ borderBottom: 'solid 1px gray' }}>
                  <th style={{ borderRight: 'solid 1px gray' }}>N°</th>
                  <th style={{ borderRight: 'solid 1px gray' }}>Nom et Prénom</th>
                  <th style={{ borderRight: 'solid 1px gray' }}>Mention</th>
                  <th>Emergement</th>
                </tr>
              </thead>
              <tbody>
                {sortedStudents.map((fi, index) => (
                  <tr key={index}>
                    <td
                      style={{
                        borderRight: 'solid 1px gray',
                        borderBottom: 'solid 1px gray',
                        padding: '5px'
                      }}
                    >
                      {index + 1}
                    </td>
                    <td
                      style={{
                        borderRight: 'solid 1px gray',
                        borderBottom: 'solid 1px gray',
                        padding: '5px'
                      }}
                    >
                      {fi.nom} {fi.prenom}
                    </td>
                    <td
                      style={{
                        borderRight: 'solid 1px gray',
                        borderBottom: 'solid 1px gray',
                        padding: '5px'
                      }}
                    >
                      {compareMention(fi.mention_id)}
                    </td>
                    <td style={{ borderBottom: 'solid 1px gray', padding: '5px' }}></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Paper>
      </div>
    </div>
  )
}

export default ModalExportFichr
