import { router } from '@inertiajs/react';
import React from 'react';

type LinkItem = {
    url: string | null;
    label: string;
    active: boolean;
};

type Props = {
    links: LinkItem[];
    className?: string;
};

function isNumberLabel(label: string) {
    return /^\d+$/.test(label);
}

function go(url: string | null) {
    if (!url) return;
    router.visit(url, { preserveState: true, preserveScroll: true });
}

function PageButton({
    item,
    children,
}: {
    item: LinkItem;
    children?: React.ReactNode;
}) {
    return (
        <button
            type="button"
            disabled={!item.url}
            onClick={() => go(item.url)}
            className={[
                'h-9 rounded-md border px-3 text-sm',
                item.active
                    ? 'border-gray-900 bg-gray-900 text-white'
                    : 'border-gray-300 bg-white hover:bg-gray-50',
                !item.url ? 'cursor-not-allowed opacity-40' : '',
            ].join(' ')}
        >
            {children ?? item.label}
        </button>
    );
}

export default function Pagination({ links, className }: Props) {
    if (!links || links.length < 3) return null;

    const prev = links[0];
    const next = links[links.length - 1];

    const pages = links
        .slice(1, -1)
        .filter((l) => isNumberLabel(String(l.label)));
    if (pages.length === 0) return null;

    const first = pages[0];
    const last = pages[pages.length - 1];

    const currentIndex = pages.findIndex((p) => p.active);
    const start = Math.max(0, currentIndex - 2);
    const end = Math.min(pages.length - 1, currentIndex + 2);
    const middle = pages.slice(start, end + 1);

    const showLeftDots = start > 1;
    const showRightDots = end < pages.length - 2;

    return (
        <div
            className={[
                'mt-4 flex flex-wrap items-center gap-2',
                className ?? '',
            ].join(' ')}
        >
            <PageButton item={prev}>Prev</PageButton>

            <PageButton item={first}>{first.label}</PageButton>

            {showLeftDots && (
                <span className="select-none px-1 text-gray-500">…</span>
            )}

            {middle
                .filter(
                    (p) => p.label !== first.label && p.label !== last.label,
                )
                .map((p) => (
                    <PageButton key={p.label} item={p}>
                        {p.label}
                    </PageButton>
                ))}

            {showRightDots && (
                <span className="select-none px-1 text-gray-500">…</span>
            )}

            {last.label !== first.label && (
                <PageButton item={last}>{last.label}</PageButton>
            )}

            <PageButton item={next}>Next</PageButton>
        </div>
    );
}
