import React from 'react';

import {
    ChevronFirstIcon,
    ChevronLastIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
    GripIcon,
} from 'lucide-react';

import AnyDropdownMenu, { MenuData } from '@/components/AnyDropdownMenu';
import { MobileFab } from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';

const FabTablePagination = ({ total, limit, offset, onChangeOffset, onChangeLimit }: { total: number, limit: number, offset: number, onChangeOffset: (offset: number) => void, onChangeLimit: (limit: number) => void }) => {

    const [currentPage, setCurrentPage] = React.useState<number>(1);
    const [pages, setPages] = React.useState<number>(Math.ceil(total / limit));

    React.useEffect(() => {
        setCurrentPage(Math.floor(offset / limit) + 1);
        setPages(Math.ceil(total / limit));
    }, [total, limit, offset]);

    const limitOptions = [10, 20, 50, 100, 200, 500];

    const onClickPage = (page: number) => {
        if (page < 1 || page > pages) {
            return;
        }
        if (page === currentPage) {
            return;
        }

        onChangeOffset((page - 1) * limit);
    }

    // Вычисляем диапазон страниц для отображения: 3 слева, текущая, 3 справа
    const startPage = Math.max(1, currentPage - 3);
    const endPage = Math.min(pages, currentPage + 3);

    // Генерируем массив страниц для отображения
    const visiblePages: number[] = [];
    for (let i = startPage; i <= endPage; i++) {
        visiblePages.push(i);
    }

    const prevPage = currentPage - 1;
    const nextPage = currentPage + 1;
    const canGoPrev = prevPage >= 1;
    const canGoNext = nextPage <= pages;


    const getMenu = () => {
        const menu: MenuData[] = [];

        menu.push({
            label: Lang.key('next_page'),
            htmlIcon: <ChevronRightIcon />,
            click: () => onClickPage(nextPage),
        });

        menu.push({
            label: Lang.key('prev_page'),
            htmlIcon: <ChevronLeftIcon />,
            click: () => onClickPage(prevPage),
        });

        menu.push({
            label: Lang.key('first_page'),
            htmlIcon: <ChevronFirstIcon />,
            click: () => onClickPage(1),
        });

        menu.push({
            label: Lang.key('last_page'),
            htmlIcon: <ChevronLastIcon />,
            click: () => onClickPage(pages),
        });

        return menu;
    }

    return <AnyDropdownMenu
        className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"
        menu={getMenu()}
    >
        <MobileFab


            icon={<GripIcon />}
            text={!!currentPage && <span className='text-base font-bold px-2'>{currentPage}</span>}
            textPosition="after"
        />
    </AnyDropdownMenu>






}

export default FabTablePagination;