'use client';

import styles from './page.module.css'
import React, {useState, useEffect} from 'react';
import { jsPDF } from "jspdf";



export default function Home() {
  type User = {
    fio: string,
  }
  const [rows, setRows] = useState<User[]>([]);

  useEffect(() => {
    async function getData() {
      const actualData = await fetch('api/load')
        .then(response => response.json());
      setRows(actualData);
    }
    getData()
  }, [])


  const print = (e: any) => {
    const key = e.target.value;

    var pdf = new jsPDF("landscape");;
    pdf.addFont("/PT_Sans/PTSans-Regular.ttf", "PTSans", "normal");
    pdf.setFont("PTSans"); // set font

    pdf.setFontSize(33);
    pdf.addImage("/sert.png", "JPEG", 0, 0, 297, 210);
    pdf.text(rows[key].fio, 60, 117);
   
    pdf.save(rows[key].fio+"_МедиаКОТ"+".pdf");
  }

  return (
    <>
    <div className="navbar bg-base-100">
        <a className="btn btn-ghost normal-case text-xl">ОБРАЗОВАТЕЛЬНЫЙ ИНТЕНСИВ МедиаКот</a>
    </div>
    <main className={styles.main}>
      <div className="card lg:card-side bg-base-100 shadow-xl">
        <div className="overflow-x-auto">
          <table className="table table-zebra w-full">
            <thead>
              <tr>
                <th></th>
                <th>ФИО</th>
                <th>Сертификат</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row, key) => (
                <tr key={key}>
                  <th>{key+1}</th>
                  <td>{row.fio}</td>
                  <td>
                    <button 
                      className="btn btn-accent" 
                      value={key}
                      onClick={(e) => print(e)}
                      >
                      Скачать
                    </button>
                  </td>
                </tr>
              ))}  
            </tbody>
          </table>
        </div>
      </div>
    </main>
    </>
  )
}
