import { useState, useEffect } from 'react';
import progressService from '../services/serviceProgress';

const useProgressClass = (progressId) => {
    const [progress, setProgress] = useState([]);
    const [section, setSection] = useState('section');
    const [topic, setTopic] = useState('topic');
    const [name, setName] = useState('class');

    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);
        const [classId, topicId] = progressId.split("&");

        const dataId = {
            ID_CLASS: classId,
            ID_TOPIC: topicId,
        };

        try {
            const data = await progressService.fetchDataClassProgress(dataId, 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_CLASS)
        } 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, progressId]);

    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 handleDownloadCSV = async () => {
        try {
            const [classId, topicId] = progressId.split("&");
    
            const dataId = {
                ID_CLASS: classId,
                ID_TOPIC: topicId,
            };
            const response = await progressService.getCsvProgress(dataId);
    
            const blob = new Blob([response], { type: '.csv' });
            const downloadUrl = URL.createObjectURL(blob);
    
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = `progress ${name} - ${topic}.csv`;
            link.click();
    
            URL.revokeObjectURL(downloadUrl);
        } catch (error) {
            console.error('Error downloading file:', error);
            alert('Gagal mengunduh file');
        }
    }

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

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

export default useProgressClass;
