import { useState, useEffect } from 'react';
import dashboardService from '../services/serviceDashboard';

const useDashboard = () => {
    const [totalStudent, setTotalStudent] = useState("-");
    const [totalTeacher, setTotalTeacher] = useState("-");
    const [reports, setReports] = useState([]);
    const [loadingReports, setLoadingReports] = useState(true);
    const [activity, setActivity] = useState([]);
    const [loadingActivity, setLoadingActivity] = useState(true);
    const [error, setError] = useState(null);
    
    const fetchTotalStudent = async () => {
        try {
            const data = await dashboardService.fetchTotalStudent("", "", 1, 0);
            setTotalStudent(data.payload.totalStudents);
        } catch (err) {
            setError(err);
        }
    };
    
    const fetchTotalTeacher = async () => {
        try {
            const data = await dashboardService.fetchTotalTeacher("", "", 1, 0);
            setTotalTeacher(data.payload.totalTeachers);
        } catch (err) {
            setError(err);
        }
    };
    
    const fetchActivity = async () => {
        setLoadingActivity(true);
        try {
            const data = await dashboardService.fetchActivity("", "", 1, 5);
            setActivity(data.payload.studentActivities);
        } catch (err) {
            setError(err);
        } finally {
            setLoadingActivity(false);
        }
    };

    const fetchReport = async () => {
        setLoadingReports(true);
        try {
            const data = await dashboardService.fetchReport("", "", 1, 5);
            setReports(data.payload.reports);
        } catch (err) {
            setError(err);
        } finally {
            setLoadingReports(false);
        }
    };

    useEffect(() => {
        fetchTotalStudent(),
        fetchTotalTeacher(),
        fetchActivity();
        fetchReport();
    }, []);

    

    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';
    }

    return { 
        error,
        totalStudent,
        totalTeacher,
        reports,
        activity,
        loadingReports,
        loadingActivity,
        formatLocalDate
    };
};

export default useDashboard;
