import React from 'react';

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

import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuGroup,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { MobileButton } from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';

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

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 } = useAppConfigStore();
    const [currentPage, setCurrentPage] = React.useState<number>(1);
    const [pages, setPages] = React.useState<number>(Math.max(1, Math.ceil(total / limit) || 1));

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

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

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

    const from = total === 0 ? 0 : offset + 1;
    const to = Math.min(offset + limit, total);
    const canGoFirst = total > 0 && currentPage > 1;
    const canGoPrev = canGoFirst;
    const canGoNext = total > 0 && currentPage < pages;
    const canGoLast = canGoNext;
    const prevPage = currentPage - 1;
    const nextPage = currentPage + 1;

    const rangeText = `${from}–${to} ${Lang.key('pagination_range_of')} ${total}`;
    const pageText = `${Lang.key('page')} ${currentPage} / ${pages}`;

    const limitDropdown = !mini && (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                {isMobile ? (
                    <MobileButton rounded outline className='px-3 whitespace-nowrap'>
                        {limit} {Lang.key('items_per_page')}
                    </MobileButton>
                ) : (
                    <Button size="sm" variant="outline">{limit} {Lang.key('items_per_page')}</Button>
                )}
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-40" align="end">
                <DropdownMenuGroup>
                    {limitOptions.map((option) => (
                        <DropdownMenuItem key={option} onClick={() => onChangeLimit(option)}>
                            {option}
                        </DropdownMenuItem>
                    ))}
                </DropdownMenuGroup>
            </DropdownMenuContent>
        </DropdownMenu>
    );

    if (isMobile) {
        return (
            <div className='flex items-center gap-2 justify-between mt-2 mx-2 text-sm'>
                {!mini && (
                    <span className='text-muted-foreground tabular-nums'>{rangeText}</span>
                )}

                <div className={`flex items-center gap-2 ${mini ? 'mx-auto' : 'ml-auto'}`}>
                    {limitDropdown}

                    <MobileButton
                        rounded
                        outline
                        onClick={() => onClickPage(1)}
                        aria-disabled={!canGoFirst}
                        aria-label={Lang.key('first_page')}
                        className={!canGoFirst ? 'pointer-events-none opacity-50 px-3' : 'cursor-pointer px-3'}
                    >
                        <ChevronFirstIcon className='size-4' />
                    </MobileButton>

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

                    <span className='text-muted-foreground tabular-nums whitespace-nowrap px-1'>
                        {pageText}
                    </span>

                    <MobileButton
                        rounded
                        outline
                        onClick={() => onClickPage(nextPage)}
                        aria-disabled={!canGoNext}
                        aria-label={Lang.key('next_page')}
                        className={!canGoNext ? 'pointer-events-none opacity-50 px-3' : 'cursor-pointer px-3'}
                    >
                        <ChevronRightIcon className='size-4' />
                    </MobileButton>

                    <MobileButton
                        rounded
                        outline
                        onClick={() => onClickPage(pages)}
                        aria-disabled={!canGoLast}
                        aria-label={Lang.key('last_page')}
                        className={!canGoLast ? 'pointer-events-none opacity-50 px-3' : 'cursor-pointer px-3'}
                    >
                        <ChevronLastIcon className='size-4' />
                    </MobileButton>
                </div>
            </div>
        );
    }

    return (
        <div className='flex items-center gap-4 justify-between mt-2 mx-2 text-sm'>
            {!mini && (
                <span className='text-muted-foreground tabular-nums'>{rangeText}</span>
            )}

            <div className={`flex items-center gap-2 ${mini ? 'mx-auto' : 'ml-auto'}`}>
                {limitDropdown}

                <Button
                    size="sm"
                    variant="outline"
                    onClick={() => onClickPage(1)}
                    aria-disabled={!canGoFirst}
                    aria-label={Lang.key('first_page')}
                    className={!canGoFirst ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                >
                    <ChevronFirstIcon className='size-4' />
                </Button>

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

                <span className='text-muted-foreground tabular-nums whitespace-nowrap'>
                    {pageText}
                </span>

                <Button
                    size="sm"
                    variant="outline"
                    onClick={() => onClickPage(nextPage)}
                    aria-disabled={!canGoNext}
                    aria-label={Lang.key('next_page')}
                    className={!canGoNext ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                >
                    <ChevronRightIcon className='size-4' />
                </Button>

                <Button
                    size="sm"
                    variant="outline"
                    onClick={() => onClickPage(pages)}
                    aria-disabled={!canGoLast}
                    aria-label={Lang.key('last_page')}
                    className={!canGoLast ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                >
                    <ChevronLastIcon className='size-4' />
                </Button>
            </div>
        </div>
    );
}

export default TablePagination;
