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

const Breadcrumb = ({ categoryId }) => {
  const breadcrumbs = useQuery(
    ['category-breadcrumbs', categoryId],
    async () =>
      await odooApi('GET', `/api/v1/category/${categoryId}/category-breadcrumb`)
  );

  const items = breadcrumbs.data ?? [];
  const lastIdx = items.length - 1;

  return (
    <div className='container mx-auto py-4 md:py-6'>
      <Skeleton isLoaded={!breadcrumbs.isLoading} className='w-full'>
        <ChakraBreadcrumb
          spacing='8px'
          sx={{
            // mobile boleh wrap; desktop tetap 1 baris
            '& ol': {
              display: 'flex',
              flexWrap: { base: 'wrap', md: 'nowrap' },
              alignItems: 'center',
            },
            '& li': { display: 'inline-flex', alignItems: 'center' },
            // semua item sebelum terakhir: jangan pernah wrap (tetap di baris atas)
            '& li:not(:last-of-type)': {
              flex: '0 0 auto',
              whiteSpace: 'nowrap',
            },
            // item terakhir: boleh ambil sisa lebar & wrap jika perlu
            '& li:last-of-type': {
              flex: '1 1 auto',
              minWidth: 0,
            },
          }}
        >
          {/* Home */}
          <BreadcrumbItem>
            <BreadcrumbLink as={Link} href='/' className='!text-danger-500'>
              Home
            </BreadcrumbLink>
          </BreadcrumbItem>

          {/* Categories */}
          {items.map((category, index) => {
            const isLast = index === lastIdx;
            return (
              <BreadcrumbItem key={index} isCurrentPage={isLast}>
                {isLast ? (
                  // HANYA yang terakhir boleh turun/wrap di mobile
                  <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
                    {category.name}
                  </BreadcrumbLink>
                ) : (
                  <BreadcrumbLink
                    as={Link}
                    href={createSlug(
                      '/shop/category/',
                      category.name,
                      category.id
                    )}
                    className='!text-danger-500'
                  >
                    {category.name}
                  </BreadcrumbLink>
                )}
              </BreadcrumbItem>
            );
          })}
        </ChakraBreadcrumb>
      </Skeleton>
    </div>
  );
};

export default Breadcrumb;
