import { IconButton } from '@/components/common/IconButton';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useI18n } from '@/hooks/use-i18n';
import { buildPaginationItems, getPaginationRange } from '@/lib/pagination';
import { cn } from '@/lib/utils';
import type { TablePaginationMeta } from '@/types/pagination';

export interface TablePaginationProps {
    meta: TablePaginationMeta;
    onPageChange: (page: number) => void;
    onPerPageChange?: (perPage: number) => void;
    isLoading?: boolean;
    perPageOptions?: number[];
    className?: string;
}

const DEFAULT_PER_PAGE_OPTIONS = [10, 15, 25, 50];

const paginationControlClass =
    'size-8 shrink-0 p-0 text-sm font-medium tabular-nums shadow-none';

export function TablePagination({
    meta,
    onPageChange,
    onPerPageChange,
    isLoading = false,
    perPageOptions = DEFAULT_PER_PAGE_OPTIONS,
    className,
}: TablePaginationProps) {
    const { t } = useI18n();
    const { from, to } = getPaginationRange(meta);
    const pageItems = buildPaginationItems(meta.current_page, meta.last_page);
    const showPageControls = meta.last_page > 1;

    if (meta.total === 0) {
        return (
            <div
                className={cn(
                    'flex items-center justify-between border-t border-border/60 px-4 py-3',
                    className,
                )}
            >
                <p className="text-sm text-muted-foreground">{t('common.pagination.no_results')}</p>
            </div>
        );
    }

    return (
        <div
            className={cn(
                'flex flex-col gap-4 border-t border-border/60 bg-muted/15 px-4 py-3 sm:flex-row sm:items-center sm:justify-between',
                className,
            )}
        >
            <p className="text-sm text-muted-foreground tabular-nums">
                {t('common.pagination.showing', { from, to, total: meta.total })}
            </p>

            <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:gap-4">
                {onPerPageChange ? (
                    <div className="flex items-center justify-between gap-2 sm:justify-start">
                        <Label
                            htmlFor="table-pagination-per-page"
                            className="shrink-0 text-sm font-normal text-muted-foreground"
                        >
                            {t('common.pagination.rows_per_page')}
                        </Label>
                        <Select
                            value={String(meta.per_page)}
                            onValueChange={(value) => onPerPageChange(Number(value))}
                            disabled={isLoading}
                        >
                            <SelectTrigger
                                id="table-pagination-per-page"
                                size="sm"
                                className="h-8 w-[4.5rem] bg-background"
                            >
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent align="end">
                                {perPageOptions.map((option) => (
                                    <SelectItem key={option} value={String(option)}>
                                        {option}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                ) : null}

                {showPageControls ? (
                    <nav
                        aria-label={t('common.pagination.nav_label')}
                        className="flex items-center justify-center gap-1"
                    >
                        <IconButton
                            type="button"
                            variant="outlined"
                            size="sm"
                            className={paginationControlClass}
                            disabled={meta.current_page <= 1 || isLoading}
                            onClick={() => onPageChange(meta.current_page - 1)}
                            aria-label={t('common.pagination.previous')}
                            icon="solar:alt-arrow-left-linear"
                        />

                        <div className="hidden items-center gap-0.5 sm:flex">
                            {pageItems.map((item, index) =>
                                item === 'ellipsis' ? (
                                    <span
                                        key={`ellipsis-${index}`}
                                        className="flex size-8 items-center justify-center text-sm text-muted-foreground"
                                        aria-hidden
                                    >
                                        …
                                    </span>
                                ) : (
                                    <Button
                                        key={item}
                                        type="button"
                                        variant="outline"
                                        size="icon"
                                        className={cn(
                                            paginationControlClass,
                                            item === meta.current_page
                                                ? 'border-primary bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground'
                                                : 'border-transparent bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground',
                                            item === meta.current_page && 'pointer-events-none',
                                        )}
                                        disabled={isLoading}
                                        aria-label={t('common.pagination.page', { page: item })}
                                        aria-current={item === meta.current_page ? 'page' : undefined}
                                        onClick={() => onPageChange(item)}
                                    >
                                        {item}
                                    </Button>
                                ),
                            )}
                        </div>

                        <span className="flex h-8 items-center px-2 text-sm tabular-nums text-muted-foreground sm:hidden">
                            {t('common.pagination.page_of', {
                                current: meta.current_page,
                                last: meta.last_page,
                            })}
                        </span>

                        <IconButton
                            type="button"
                            variant="outlined"
                            size="sm"
                            className={paginationControlClass}
                            disabled={meta.current_page >= meta.last_page || isLoading}
                            onClick={() => onPageChange(meta.current_page + 1)}
                            aria-label={t('common.pagination.next')}
                            icon="solar:alt-arrow-right-linear"
                        />
                    </nav>
                ) : (
                    <p className="text-center text-sm text-muted-foreground sm:text-end">
                        {t('common.pagination.single_page')}
                    </p>
                )}
            </div>
        </div>
    );
}
