import Breadcrumb from "@/app/components/Breadcrumb";
import NewsSection from "@/app/blog/components/NewsSection";
import Sidebar from "@/app/blog/components/Sidebar";
import { fetchBlogsByTag, fetchTagDetail } from "@/api/blogsApi";

interface TagPageProps {
  params:
    | Promise<{
        slug: string;
      }>
    | {
        slug: string;
      };
  searchParams?: Promise<{ search?: string; page?: string }> | { search?: string; page?: string };
}

export default async function TagPage({ params, searchParams }: TagPageProps) {
    // Handle both Promise and direct object
    const resolvedParams = params instanceof Promise ? await params : params;
    const slug = resolvedParams.slug;
    const resolvedSearchParams =
      searchParams instanceof Promise ? await searchParams : searchParams;
    const searchQuery = resolvedSearchParams?.search?.toString() || "";
    const pageParam = resolvedSearchParams?.page?.toString() || "1";
    const currentPage = Number.parseInt(pageParam, 10) || 1;

    // Fetch tag detail and blogs
    let tagResponse, blogsResponse;
    try {
        [tagResponse, blogsResponse] = await Promise.all([
            fetchTagDetail(slug),
            fetchBlogsByTag(slug, {
              page: currentPage,
              limit: 3,
              ...(searchQuery ? { search: searchQuery } : {}),
            }),
        ]);
    } catch {
        return (
            <>
                <Breadcrumb title="Tag" current="Blog Tag" />
                <section className="news-standard-section section-padding fix">
                    <div className="container">
                        <div className="news-standard-wrapper">
                            <div className="row g-4">
                                <div className="col-lg-8 col-12">
                                    <div className="py-5">
                                        <h2>Tag not found</h2>
                                        <p>The tag you are looking for does not exist.</p>
                                    </div>
                                </div>
                                <Sidebar />
                            </div>
                        </div>
                    </div>
                </section>
            </>
        );
    }

    const tag = tagResponse.data;
    const { blogs, pagination } = blogsResponse.data;

    return (
        <>
            <Breadcrumb title={tag.name} current="Blog Tag" />
            <NewsSection blogs={blogs} tagSlug={slug} searchQuery={searchQuery} pagination={pagination} />
        </>
    );
}
