import odooApi from '@/core/api/odooApi'
import { createSlug } from '@/core/utils/slug'
import {
  Breadcrumb as ChakraBreadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  Skeleton
} from '@chakra-ui/react'
import classNames from 'classnames'
import Link from 'next/link'
import { useQuery } from 'react-query'

/**
 * Renders a breadcrumb component based on the provided `productId`.
 *
 * @param {Object} props - The properties passed to the component.
 * @param {number} props.productId - The ID of the product.
 * @param {string} props.productName - The ID of the product.
 * @return {ReactElement} The rendered breadcrumb component.
 */
const Breadcrumb = ({ productId, productName }) => {
  const categories = useQuery(
    `detail/categories/${productId}`,
    async () => await odooApi('GET', `/api/v1/product/${productId}/category-breadcrumb`),
    {
      enabled: !!productId
    }
  )

  return (
    <Skeleton
      isLoaded={!categories.isLoading}
      className={classNames({
        'w-2/3': categories.isLoading,
        'w-full': !categories.isLoading
      })}
    >
      <ChakraBreadcrumb
        mb={10}
        overflowX={'auto'}
        className='text-caption-2 md:text-body-2 p-4 md:p-0'
      >
        <BreadcrumbItem>
          <BreadcrumbLink as={Link} href='/' className='!text-danger-500 whitespace-nowrap'>
            Home
          </BreadcrumbLink>
        </BreadcrumbItem>

        {categories.data?.map((category) => (
          <BreadcrumbItem key={category.id}>
            <BreadcrumbLink
              as={Link}
              href={createSlug('/shop/category/', category.name, category.id)}
              className='!text-danger-500 whitespace-nowrap'
            >
              {category.name}
            </BreadcrumbLink>
          </BreadcrumbItem>
        ))}

        <BreadcrumbItem isCurrentPage>
          <BreadcrumbLink className='whitespace-nowrap'>{productName}</BreadcrumbLink>
        </BreadcrumbItem>
      </ChakraBreadcrumb>
    </Skeleton>
  )
}

export default Breadcrumb
