import React, { useState, useEffect } from 'react';
import { Pagination } from 'antd';
import DocumentCard from './DocumentCard';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useWindowResize } from '../../Hooks/useWindowResize';
import { useGetCertificate } from '../../api/certificate';

const Document: React.FC = () => {
    const { t } = useTranslation();
    const [isChanging, setIsChanging] = useState(false);
    const { windowWidth } = useWindowResize();
    
    const [currentPage, setCurrentPage] = useState(1);
    const [totalItems, setTotalItems] = useState(0);
    const [perPage, setPerPage] = useState(3);
    const { data } = useGetCertificate({ page: currentPage, per_page: perPage });
    
    const navigate = useNavigate();
    const location = useLocation();

    const handlePageChange = (page: number) => {
        setIsChanging(true);
        setTimeout(() => {
            setCurrentPage(page);
            navigate(`${location.pathname}?page=${page}`);
            setIsChanging(false);
        }, 300);
    };

    useEffect(() => {
        const params = new URLSearchParams(location.search);
        const pageParam = params.get('page');
        const page = pageParam ? parseInt(pageParam, 10) : 1;
        setCurrentPage(page);
    }, [location.search]);

    useEffect(() => {
        if (data?.meta) {
            setTotalItems(data.meta.total);
        }
    }, [data]);

    useEffect(() => {
        if (windowWidth < 600) {
            setPerPage(1);
        } else if (windowWidth < 1300) {
            setPerPage(2);
        } else {
            setPerPage(3);
        }
    }, [windowWidth]);

    return (
        <div className='Document'>
            <h1>{t("Documents")}</h1>
            <h2>{t("Quality Certificates")}</h2>

            <Pagination
                current={currentPage}
                pageSize={perPage}
                total={totalItems}
                onChange={handlePageChange}
            />
            <div className={`document-cards ${isChanging ? 'changing' : ''}`}>
                {data?.data?.map((item: any) => (
                    <DocumentCard
                        key={item.id}
                        name={item?.name}
                        image={item?.image}
                    />
                ))}
            </div>
        </div>
    );
};

export default Document;