import { useState, useEffect } from 'react';
import progressService from '../services/serviceProgress';
import jsPDF from "jspdf";
import "jspdf-autotable";

const useProgressStudent = (monitoringId) => {
    const [progress, setProgress] = useState([]);
    const [section, setSection] = useState('section');
    const [topic, setTopic] = useState('topic');
    const [name, setName] = useState('name');
    const [nisn, setNisn] = useState('nisn');

    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const [search, setSearch] = useState("");
    const [sort, setSort] = useState("");
    const [page, setCurrentPage] = useState(1);
    const [limit, setLimit] = useState(20);
    const [totalPages, setTotalPages] = useState(0);
    const [totalData, setTotalData] = useState(null);
    
    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await progressService.fetchDataStudentProgress(monitoringId, search, sort, page, limit);
            setProgress(data.payload.levels);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);

            setSection(data.payload.NAME_SECTION)
            setTopic(data.payload.NAME_TOPIC)
            setName(data.payload.NAME_USERS)
            setNisn(data.payload.NISN)
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSearchChange = () => {
        fetchData();
        setCurrentPage(1);
    }

    const handlePageChange = (pages) => {
        setCurrentPage(pages);
    }

    const handleLimitsChange = (e) => {
        setLimit(e.target.value);
        setCurrentPage(1);
    }

    useEffect(() => {
        fetchData();
    }, [page, limit, monitoringId]);

    function formatLocalDate(isoDate) {
        const date = new Date(isoDate);
    
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
            timeZone: 'Asia/Jakarta'
        };
        
        return new Intl.DateTimeFormat('id-ID', options).format(date)
            .replace(/\//g, '-')
            .replace(/\./g, ':') + ' WIB';
    }

    const downloadPDF = () => {
        const doc = new jsPDF();
        const pageWidth = doc.internal.pageSize.getWidth();

        const text = "Progress Report";
        const textWidth = doc.getTextWidth(text);
        const titleCenter = (pageWidth - textWidth) / 2;
        
        doc.setFontSize(14);
        doc.text(text, titleCenter, 12);
        
        doc.setFontSize(12);
        doc.text(name, 14, 24);
        doc.text(nisn.toString(), 14, 30);
        doc.setFontSize(10);
        doc.text(`${section} - ${topic}`, 14, 36);
    
        const columns = ["No", "Name", "Score", "Feedback", "Start Exercise", "Finish Exercise"];
        const rows = progress.map((item, index) => [(index+1), item.NAME_LEVEL, item.SCORE, item.FEEDBACK_STUDENT, formatLocalDate(item.STUDENT_START), formatLocalDate(item.STUDENT_FINISH)]);
    
        doc.autoTable({
          head: [columns],
          body: rows,
          startY: 44,
        });

        doc.save(`SEALS-report-${name}.pdf`);
    };

    return { 
        progress,
        section,
        topic,
        name,
        nisn,
        loading, 
        error, 

        totalPages,
        totalData,
        setSearch,
        page, 
        handlePageChange,
        handleLimitsChange,
        handleSearchChange,
        formatLocalDate,
        downloadPDF
    };
};

export default useProgressStudent;
