'use client'
import { NextPage } from 'next'
import { useState } from 'react'
import Layout from '@/hoc/Layout'
import Categories from './components/Categories'
import BlogItem from './components/BlogItem'
import LastPost from './components/LastPost'
import Pagination from './components/Pagination'
import { useGetBlogCategories, useGetBlogs, useGetBlogsByCategory } from './hooks/useBlogData'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'

const BlogsPage: NextPage = () => {
    const [currentPage, setCurrentPage] = useState(1)
    const [selectedCategory, setSelectedCategory] = useState<string | null>(null)

    const { data: blogCategories, isLoading: categoriesLoading, error: categoriesError } = useGetBlogCategories()

    // Always call both hooks, but use the appropriate one
    const { data: allBlogs, isLoading: allBlogsLoading, error: allBlogsError } = useGetBlogs(currentPage, 10)
    const { data: categoryBlogs, isLoading: categoryBlogsLoading, error: categoryBlogsError } = useGetBlogsByCategory(selectedCategory || '', currentPage, 10)

    // Use the appropriate data based on selected category
    const blogs = selectedCategory ? categoryBlogs : allBlogs
    const blogsLoading = selectedCategory ? categoryBlogsLoading : allBlogsLoading
    const blogsError = selectedCategory ? categoryBlogsError : allBlogsError

    if (blogsLoading || categoriesLoading) {
        return <PageLoading />
    }

    if (blogsError || categoriesError) {
        return <Error errorText="خطا در بارگذاری مطالب" />
    }

    const handlePageChange = (page: number) => {
        setCurrentPage(page)
        window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    const handleCategorySelect = (slug: string | null) => {
        setSelectedCategory(slug)
        setCurrentPage(1) // Reset to first page when changing category
    }

    const pager = blogs?.results?.pager

    return (
        <div className='flex flex-col lg:flex-row gap-6 lg:gap-24 p-4 sm:p-6 lg:p-10'>
            {/* Categories - Hidden on mobile, shown on desktop */}
            <div className='hidden lg:block'>
                <Categories
                    categories={blogCategories || []}
                    selectedCategory={selectedCategory}
                    onCategorySelect={handleCategorySelect}
                />
            </div>

            {/* Main content */}
            <div className='flex-1 flex flex-col gap-6'>
                {blogs?.results?.blogs?.map((blog) => (
                    <BlogItem key={blog._id} blog={blog} />
                ))}

                {/* Pagination */}
                {pager && (
                    <Pagination
                        currentPage={currentPage}
                        totalPages={pager.totalPages}
                        totalItems={pager.totalItems}
                        itemsPerPage={10}
                        onPageChange={handlePageChange}
                    />
                )}
            </div>

            {/* Last Post - Full width on mobile, sidebar on desktop */}
            <div className='lg:max-w-[340px] w-full'>
                <LastPost blogs={blogs?.results?.blogs?.slice(0, 2) || []} />
            </div>
        </div>
    )
}

export default function BlogsPageWithLayout() {
    return (
        <Layout>
            <BlogsPage />
        </Layout>
    )
}
