"use client";

import { useState } from "react";

interface Post {
    ID: string | number;
    post_title: string;
    post_name: string;
    post_excerpt: string | null;
    post_date: string;
}

interface GridData {
    id: string | number;
    title: string;
    page: number;
    perPage: number;
    total: number;
    totalPages: number;
    posts: Post[];
}

function getPageRange(current: number, total: number) {
    const range: (number | "...")[] = [];
    const delta = 2;

    const left = Math.max(2, current - delta);
    const right = Math.min(total - 1, current + delta);

    range.push(1);

    if (left > 2) range.push("...");

    for (let i = left; i <= right; i++) range.push(i);

    if (right < total - 1) range.push("...");

    if (total > 1) range.push(total);

    return range;
}

export default function PostGridClient({ initialData }: { initialData: GridData }) {
    const [data, setData] = useState(initialData);
    const [loading, setLoading] = useState(false);

    async function goToPage(page: number) {
        if (page === data.page || page < 1 || page > data.totalPages) return;

        setLoading(true);
        const res = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:3490"}/api/post-grids/${data.id}?page=${page}`
        );

        const json = await res.json();
        setData(json);
        setLoading(false);
    }

    const pages = getPageRange(data.page, data.totalPages);

    return (
        <section className="post-grid">
            <div className="grid">
                {data.posts.map(post => (
                    <article key={post.ID}>
                        <h3>
                            <a href={`/${post.post_name}`}>{post.post_title}</a>
                        </h3>
                        {post.post_excerpt && <p>{post.post_excerpt}</p>}
                    </article>
                ))}
            </div>

            {data.totalPages > 1 && (
                <nav className="pagination" aria-label="Pagination">
                    <button
                        disabled={data.page === 1 || loading}
                        onClick={() => goToPage(data.page - 1)}
                    >
                        ← Prev
                    </button>

                    {pages.map((p, i) =>
                        p === "..." ? (
                            <span key={`ellipsis-${i}`} className="ellipsis">
                                …
                            </span>
                        ) : (
                            <button
                                key={`page-${p}-${i}`}
                                disabled={p === data.page || loading}
                                aria-current={p === data.page ? "page" : undefined}
                                onClick={() => goToPage(p as number)}
                            >
                                {p}
                            </button>
                        )
                    )}


                    <button
                        disabled={data.page === data.totalPages || loading}
                        onClick={() => goToPage(data.page + 1)}
                    >
                        Next →
                    </button>
                </nav>
            )}
        </section>
    );
}
