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 { Lang } from '@/lang/Lang';
import { cn } from '@/lib/utils';
import useAppConfigStore from '@/stores/appConfig';

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

const segmentButtonClass = (disabled: boolean) =>
    cn(
        'flex h-11 w-10 shrink-0 items-center justify-center border-border active:bg-muted',
        !disabled ? 'cursor-pointer' : 'pointer-events-none opacity-40',
    );

const TablePagination = ({ total, limit, offset, onChangeOffset, mini, onChangeLimit, className }: { mini?: boolean, total: number, limit: number, offset: number, onChangeOffset: (offset: number) => void, onChangeLimit: (limit: number) => void, className?: string }) => {
    const { isMobile } = useAppConfigStore();

    const safeLimit = limit > 0 ? limit : defaultLimit;
    const safeOffset = Number.isFinite(offset) ? offset : 0;
    const safeTotal = Number.isFinite(total) ? total : 0;

    const pages = safeTotal === 0 ? 1 : Math.max(1, Math.ceil(safeTotal / safeLimit));
    const currentPage = Math.max(1, Math.min(pages, Math.floor(safeOffset / safeLimit) + 1));

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

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

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

    const rangeText = `${from}–${to} ${Lang.key('pagination_range_of')} ${safeTotal}`;
    const pageText = `${Lang.key('page')} ${currentPage} / ${pages}`;
    const mobilePageOfText = `${currentPage} ${Lang.key('pagination_range_of')} ${pages}`;
    const mobilePerRecordsText = `${Lang.key('pagination_mobile_per')} ${safeLimit} ${Lang.key('pagination_mobile_records')}`;

    const limitDropdown = !mini && (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button size="sm" variant="outline">{safeLimit} {Lang.key('items_per_page')}</Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-40" align="center">
                <DropdownMenuGroup>
                    {limitOptions.map((option) => (
                        <DropdownMenuItem key={option} onClick={() => onChangeLimit(option)}>
                            {option}
                        </DropdownMenuItem>
                    ))}
                </DropdownMenuGroup>
            </DropdownMenuContent>
        </DropdownMenu>
    );

    if (isMobile) {
        const centerContent = (
            <>
                <span className="font-medium tabular-nums leading-tight">{mobilePageOfText}</span>
                {!mini && (
                    <span className="text-[11px] leading-tight text-muted-foreground tabular-nums">
                        {mobilePerRecordsText}
                    </span>
                )}
            </>
        );

        return (
            <div className={cn('flex w-full overflow-hidden rounded-md border border-border bg-background', className)}>
                <button
                    type="button"
                    onClick={() => onClickPage(prevPage)}
                    aria-disabled={!canGoPrev}
                    aria-label={Lang.key('prev_page')}
                    className={cn(segmentButtonClass(!canGoPrev), 'border-r')}
                >
                    <ChevronLeftIcon className="size-6" />
                </button>

                <button
                    type="button"
                    onClick={() => onClickPage(1)}
                    aria-disabled={!canGoFirst}
                    aria-label={Lang.key('first_page')}
                    className={cn(segmentButtonClass(!canGoFirst), 'border-r')}
                >
                    <ChevronFirstIcon className="size-6" />
                </button>

                {!mini ? (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <button
                                type="button"
                                className="flex min-w-0 flex-1 flex-col items-center justify-center gap-0.5 border-r border-border px-2 py-1.5 text-xs active:bg-muted"
                                aria-label={Lang.key('items_per_page')}
                            >
                                {centerContent}
                            </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="w-40" align="center">
                            <DropdownMenuGroup>
                                {limitOptions.map((option) => (
                                    <DropdownMenuItem key={option} onClick={() => onChangeLimit(option)}>
                                        {option}
                                    </DropdownMenuItem>
                                ))}
                            </DropdownMenuGroup>
                        </DropdownMenuContent>
                    </DropdownMenu>
                ) : (
                    <div className="flex min-w-0 flex-1 flex-col items-center justify-center gap-0.5 border-x border-border px-2 py-1.5 text-xs">
                        {centerContent}
                    </div>
                )}

                <button
                    type="button"
                    onClick={() => onClickPage(pages)}
                    aria-disabled={!canGoLast}
                    aria-label={Lang.key('last_page')}
                    className={cn(segmentButtonClass(!canGoLast), 'border-r')}
                >
                    <ChevronLastIcon className="size-6" />
                </button>

                <button
                    type="button"
                    onClick={() => onClickPage(nextPage)}
                    aria-disabled={!canGoNext}
                    aria-label={Lang.key('next_page')}
                    className={segmentButtonClass(!canGoNext)}
                >
                    <ChevronRightIcon className="size-6" />
                </button>
            </div>
        );
    }

    return (
        <div className='@container flex items-center gap-2 justify-between mt-2 mx-2 text-sm'>
            {!mini && (
                <span className='hidden @[26rem]:inline text-muted-foreground tabular-nums whitespace-nowrap'>{rangeText}</span>
            )}

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

                <Button
                    size="icon-sm"
                    variant="outline"
                    onClick={() => onClickPage(1)}
                    aria-disabled={!canGoFirst}
                    tooltip={Lang.key('first_page')}
                    aria-label={Lang.key('first_page')}
                    className={`hidden @[20rem]:inline-flex ${!canGoFirst ? 'pointer-events-none opacity-50' : 'cursor-pointer'}`}
                >
                    <ChevronFirstIcon className='size-4' />
                </Button>

                <Button
                    size="icon-sm"
                    variant="outline"
                    onClick={() => onClickPage(prevPage)}
                    aria-disabled={!canGoPrev}
                    tooltip={Lang.key('prev_page')}
                    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 px-1'>
                    {pageText}
                </span>

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

                <Button
                    size="icon-sm"
                    variant="outline"
                    onClick={() => onClickPage(pages)}
                    aria-disabled={!canGoLast}
                    tooltip={Lang.key('last_page')}
                    aria-label={Lang.key('last_page')}
                    className={`hidden @[20rem]:inline-flex ${!canGoLast ? 'pointer-events-none opacity-50' : 'cursor-pointer'}`}
                >
                    <ChevronLastIcon className='size-4' />
                </Button>
            </div>
        </div>
    );
}

export default TablePagination;
