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';
import useDevice from '@/core/hooks/useDevice';

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

  const { isDesktop, isMobile } = useDevice();
  const items = breadcrumbs.data ?? [];

  /* =========================
     DESKTOP
  ========================= */
  if (isDesktop) {
    return (
      <div className='container mx-auto py-4 md:py-6'>
        <Skeleton isLoaded={!breadcrumbs.isLoading} className='w-2/3'>
          <ChakraBreadcrumb
            spacing='8px'
            sx={{
              '& ol': {
                display: 'flex',
                flexWrap: { base: 'wrap', md: 'nowrap' },
                alignItems: 'center',
              },
              '& li': { display: 'inline-flex', alignItems: 'center' },
              '& li:not(:last-of-type)': {
                flex: '0 0 auto',
                whiteSpace: 'nowrap',
              },
              '& 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 isLastCategory = index === items.length - 1;
              const isClickable = currentLabel || !isLastCategory;

              return (
                <BreadcrumbItem key={index} isCurrentPage={!isClickable}>
                  {isClickable ? (
                    <BreadcrumbLink
                      as={Link}
                      href={createSlug(
                        '/shop/category/',
                        category.name,
                        category.id,
                      )}
                      className='!text-danger-500'
                    >
                      {category.name}
                    </BreadcrumbLink>
                  ) : (
                    <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
                      {category.name}
                    </BreadcrumbLink>
                  )}
                </BreadcrumbItem>
              );
            })}

            {/* Searchkey / Current Page */}
            {currentLabel && (
              <BreadcrumbItem isCurrentPage>
                <BreadcrumbLink className='block whitespace-normal break-words md:whitespace-nowrap'>
                  {currentLabel}
                </BreadcrumbLink>
              </BreadcrumbItem>
            )}
          </ChakraBreadcrumb>
        </Skeleton>
        {shortDesc && (
          <div
            className='
    w-full mt-2
    text-sm text-neutral-600
    leading-7
    text-justify
    break-words
    [hyphens:auto]
    max-w-none
  '
          >
            {shortDesc}
          </div>
        )}
      </div>
    );
  }

  /* =========================
     MOBILE
  ========================= */
  if (isMobile) {
    const n = items.length;
    const lastCat = n >= 1 ? items[n - 1] : null;
    const secondLast = n >= 2 ? items[n - 2] : null;
    const beforeSecond = n >= 3 ? items[n - 3] : null;

    const hiddenText =
      n >= 3
        ? items
            .slice(0, n - 2)
            .map((c) => c.name)
            .join(' / ')
        : '';

    const finalLabel = currentLabel || lastCat?.name;

    return (
      <div className='container mx-auto py-2 mt-2'>
        <Skeleton isLoaded={!breadcrumbs.isLoading} className='w-full'>
          <ChakraBreadcrumb
            separator={<span className='mx-1'>/</span>}
            spacing='4px'
            sx={{
              '& ol': {
                display: 'flex',
                alignItems: 'center',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                gap: '0',
              },
              '& li': { display: 'inline-flex', alignItems: 'center' },
              '& li:not(:last-of-type)': {
                flex: '0 0 auto',
                whiteSpace: 'nowrap',
              },
              '& li:last-of-type': {
                flex: '0 1 auto',
                minWidth: 0,
              },
            }}
            className='text-caption-2 p-0'
          >
            {/* Home */}
            <BreadcrumbItem>
              <BreadcrumbLink as={Link} href='/' className='!text-danger-500'>
                Home
              </BreadcrumbLink>
            </BreadcrumbItem>

            {/* Jika ada kategori sebelum secondLast, tampilkan '..' (link ke beforeSecond) */}
            {beforeSecond && (
              <BreadcrumbItem>
                <BreadcrumbLink
                  as={Link}
                  href={createSlug(
                    '/shop/category/',
                    beforeSecond.name,
                    beforeSecond.id,
                  )}
                  title={hiddenText}
                  className='!text-danger-500'
                >
                  ..
                </BreadcrumbLink>
              </BreadcrumbItem>
            )}

            {secondLast && (
              <BreadcrumbItem>
                <BreadcrumbLink
                  as={Link}
                  href={createSlug(
                    '/shop/category/',
                    secondLast.name,
                    secondLast.id,
                  )}
                  className='!text-danger-500'
                >
                  {secondLast.name}
                </BreadcrumbLink>
              </BreadcrumbItem>
            )}

            {/* lastCat (current) dengan truncate & lebar dibatasi */}
            {lastCat && (
              <BreadcrumbItem isCurrentPage>
                <span
                  className='inline-block truncate align-bottom'
                  style={{ maxWidth: '60vw' }}
                  title={lastCat.name}
                >
                  {finalLabel}
                </span>
              </BreadcrumbItem>
            )}
          </ChakraBreadcrumb>
        </Skeleton>

        {shortDesc && (
          <div
            className='
    w-full mt-2
    text-sm text-neutral-600
    leading-7
    text-justify
    break-words
    [hyphens:auto]
    max-w-none
  '
          >
            {shortDesc}
          </div>
        )}
      </div>
    );
  }

  return null;
};

export default Breadcrumb;
