import BasicLayout from '@/core/components/layouts/BasicLayout'
import Link from 'next/link'
import { createSlug } from '@/core/utils/slug'
import Image from '@/core/components/elements/Image/Image'
import useBlogs from '@/lib/blog/hooks/useBlogs'
import { useRouter } from 'next/router'
import Pagination from '@/core/components/elements/Pagination/Pagination'
import Spinner from '@/core/components/elements/Spinner/Spinner'

export default function Blogs() {
  const router = useRouter()
  const limit = 16

  const { page = 1 } = router.query
  const { blogs } = useBlogs({ limit, offset: limit * (page - 1) })

  const pageCount = Math.ceil(blogs?.data?.blogTotal / limit)

  return (
    <BasicLayout>
      <div className='container mx-auto p-4 md:p-0 my-0 md:my-10'>
        <h1 className='font-bold text-2xl mb-6'>Blog Indoteknik</h1>

        {blogs.isLoading && (
          <div className='flex justify-center my-6'>
            <Spinner className='w-6 text-gray_r-12/50 fill-gray_r-12' />
          </div>
        )}

        <div className='grid gap-6 grid-cols-1 md:grid-cols-4'>
          {blogs.data?.blogs?.map((blog, index) => {
            return (
              <div className='rounded shadow-sm border border-gray_r-4 h-full bg-white' key={index}>
                <Link href={createSlug('blog/', blog.title, blog.id)}>
                  <Image
                    src={blog.thumbnail}
                    alt={blog.title}
                    className='w-full h-[112px] object-cover object-center'
                  />
                </Link>
                <div className='p-3 text-gray_r-12/80'>
                  <div className='mb-1'>{blog.category.name}</div>
                  <Link
                    href={createSlug('blog/', blog.title, blog.id)}
                    className='mb-3 !text-gray_r-12/90 text-body-1 font-medium leading-6 line-clamp-2'
                  >
                    {blog.title}
                  </Link>
                  <div className='text-caption-1'>{blog.postDate}</div>
                </div>
              </div>
            )
          })}
        </div>

        <Pagination
          currentPage={parseInt(page)}
          pageCount={pageCount}
          url={`/blog`}
          className='mt-4 md:mt-10'
        />
      </div>
    </BasicLayout>
  )
}
