import { useState, useEffect } from 'react';
import reportService from '../services/serviceReports';

const useReports = () => {
    const [reports, setReports] = useState([]);
    const [selected, setSelected] = useState({
        USER_NAME : '',
        USER_EMAIL : '',
        REPORTS : '',
        TIME_REPORT : ''
    });
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const [show, setShow] = useState(false);

    const [search, setSearch] = useState("");
    const [sort, setSort] = useState("");
    const [page, setCurrentPage] = useState(1);
    const [limit, setLimit] = useState(10);
    const [totalPages, setTotalPages] = useState(0);
    const [totalData, setTotalData] = useState(null);

    const resetForm = () =>{
        setSelected({
            USER_NAME : '',
            USER_EMAIL : '',
            REPORTS : '',
            TIME_REPORT : ''
        });
    }

    const handleShow = (data) => {
        setSelected({
            USER_NAME : data?.USER_NAME || '',
            USER_EMAIL : data?.USER_EMAIL || '',
            REPORTS : data?.REPORTS || '',
            TIME_REPORT : data?.TIME_REPORT || ''
        });
        setShow(true);
    };
    const handleClose = () => {setShow(false); resetForm();};
    
    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await reportService.fetchData(search, sort, page, limit);
            setReports(data.payload.reports);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);
        } 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]);

    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 { 
        reports,
        loading, 
        error, 

        totalPages,
        totalData,
        setSearch,
        page, 
        handlePageChange,
        handleLimitsChange,
        handleSearchChange,

        selected,
        show,
        handleShow,
        handleClose,
        formatLocalDate
    };
};

export default useReports;
