import React from 'react';

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

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { MobileButton } from '@/components/ui/mobile';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

const TablePagination = ({ total, limit, offset, onChangeOffset, mini, onChangeLimit }: { mini?: boolean, total: number, limit: number, offset: number, onChangeOffset: (offset: number) => void, onChangeLimit: (limit: number) => void }) => {
    const { isMobile } = useAppConfig();
    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 = isMobile ? Math.max(1, currentPage - 1) : Math.max(1, currentPage - 3);
    const endPage = isMobile ? Math.min(pages, currentPage + 2) : 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;



    if (isMobile) {
        return (
            <div className='flex items-center gap-2 justify-between mt-2 mx-2'>
                {!mini && <div className='flex items-center gap-2'>

                    <MobileButton className='px-3' rounded>
                        {total}
                    </MobileButton>

                </div>}

                <div className='flex items-center gap-2' >

                    <MobileButton rounded
                        onClick={() => onClickPage(prevPage)}
                        aria-disabled={!canGoPrev}
                        className={!canGoPrev ? 'pointer-events-none opacity-50 px-3' : 'cursor-pointer  px-3'}>
                        <ChevronLeftIcon className='size-4' />

                    </MobileButton>


                    {visiblePages.map((page) => (
                        <MobileButton rounded
                            className={page === currentPage ? 'cursor-default  px-3' : 'cursor-pointer  px-3'}
                            outline={page !== currentPage}
                            onClick={() => onClickPage(page)}
                        >{page}</MobileButton>
                    ))}
                    <MobileButton rounded onClick={() => onClickPage(nextPage)}
                        outline={!canGoNext}
                        aria-disabled={!canGoNext}
                        className={!canGoNext ? 'pointer-events-none opacity-50  px-3' : 'cursor-pointer  px-3'}>
                        <ChevronRightIcon className='size-4' />

                    </MobileButton>


                </div>


            </div>
        )
    }

    return (<div className='flex items-center gap-2 justify-between mt-2 mx-2'>


        <div className='flex items-center gap-2'>

            <Button
                size="sm"
                variant={"outline"}
                onClick={() => onClickPage(prevPage)}
                aria-disabled={!canGoPrev}
                className={!canGoPrev ? 'pointer-events-none opacity-50' : 'cursor-pointer'}>
                <ChevronLeftIcon className='size-4' />

            </Button>


            {visiblePages.map((page) => (
                <Button
                    size="sm"
                    className={page === currentPage ? 'cursor-default' : 'cursor-pointer'}
                    variant={page === currentPage ? 'secondary' : "outline"}
                    onClick={() => onClickPage(page)}
                >{page}</Button>
            ))}
            <Button onClick={() => onClickPage(nextPage)}
                variant={"outline"}
                size="sm"
                aria-disabled={!canGoNext}
                className={!canGoNext ? 'pointer-events-none opacity-50' : 'cursor-pointer'}>
                <ChevronRightIcon className='size-4' />

            </Button>


        </div>
        {!mini && <div className='flex items-center gap-2'>

            {/* <Badge variant="outline" className='px-3'>
                {Lang.key("total")} {total}
            </Badge>
            <Badge variant="outline" className='px-3'>
                {Lang.key("page")} {currentPage} / {pages}
            </Badge>*/}

            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                    <Button size="sm" variant="outline">{limit} {Lang.key("items_per_page")}</Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="w-40" align="start">
                    <DropdownMenuGroup>
                        {limitOptions.map((limit) => (
                            <DropdownMenuItem key={limit} onClick={() => onChangeLimit(limit)}>
                                {limit}
                            </DropdownMenuItem>
                        ))}
                    </DropdownMenuGroup>

                </DropdownMenuContent>
            </DropdownMenu>

            <Button size="sm" variant="outline">{Lang.key("total")} {total}</Button>
            <Button size="sm" variant="outline">{Lang.key("page")} {currentPage} / {pages}</Button>


        </div>}


    </div>
    )

    return (<div className='flex items-center gap-2 justify-between mt-2 mx-2'>
        {!mini && <div className='flex items-center gap-2'>

            <Badge variant="outline" className='px-3'>
                {Lang.key("total")} {total}
            </Badge>
            <Badge variant="outline" className='px-3'>
                {Lang.key("page")} {currentPage} / {pages}
            </Badge>
        </div>}

        <div className='flex items-center gap-2'>

            <Badge
                variant={"outline"}
                onClick={() => onClickPage(prevPage)}
                aria-disabled={!canGoPrev}
                className={!canGoPrev ? 'pointer-events-none opacity-50' : 'cursor-pointer'}>
                <ChevronLeftIcon className='size-4' />

            </Badge>


            {visiblePages.map((page) => (
                <Badge
                    className={page === currentPage ? 'cursor-default' : 'cursor-pointer'}
                    variant={page === currentPage ? 'secondary' : "outline"}
                    onClick={() => onClickPage(page)}
                >{page}</Badge>
            ))}
            <Badge onClick={() => onClickPage(nextPage)}
                variant={"outline"}
                aria-disabled={!canGoNext}
                className={!canGoNext ? 'pointer-events-none opacity-50' : 'cursor-pointer'}>
                <ChevronRightIcon className='size-4' />

            </Badge>


        </div>


    </div>
    )
}

export default TablePagination;