import React, { Fragment } from 'react';
import { useQuery } from 'react-query';
import Link from 'next/link';
import { getProductCategoryBreadcrumb } from '~/services/product';
import { createSlug } from '~/libs/slug';
import useDevice from '@/core/hooks/useDevice';

type Props = { id: number; name: string };

const Breadcrumb = ({ id, name }: Props) => {
  const { isDesktop, isMobile } = useDevice();

  const { data } = useQuery({
    queryKey: ['product-category-breadcrumb', id],
    queryFn: () => getProductCategoryBreadcrumb(id),
    refetchOnWindowFocus: false,
  });

  const breadcrumbs = data ?? [];
  const total = breadcrumbs.length;
  const lastCat = total ? breadcrumbs[total - 1] : null;
  const hasHidden = total > 1;
  const hiddenText = hasHidden
    ? breadcrumbs
        .slice(0, total - 1)
        .map((c) => c.name)
        .join(' / ')
    : '';

  if (isMobile) {
    const crumbsMobile: React.ReactNode[] = [];

    crumbsMobile.push(
      <Link href='/' className='text-danger-500 shrink-0' key='home'>
        Home
      </Link>
    );

    if (hasHidden) {
      crumbsMobile.push(
        <span
          className='text-danger-500 shrink-0'
          title={hiddenText}
          aria-label='Kategori tersembunyi'
          key='hidden'
        >
          ..
        </span>
      );
    }

    // Kategori terakhir
    if (lastCat) {
      crumbsMobile.push(
        <Link
          key={`cat-${lastCat.id}`}
          href={createSlug('/shop/category/', lastCat.name, String(lastCat.id))}
          className='text-danger-500 shrink-0'
        >
          {lastCat.name}
        </Link>
      );
    }

    // Nama produk (dipotong kalau gk muat)
    crumbsMobile.push(
      <span className='truncate min-w-0 flex-1' title={name} key='product'>
        {name}
      </span>
    );

    return (
      <div className='flex items-center whitespace-nowrap overflow-hidden text-caption-1 leading-7'>
        {crumbsMobile.map((node, i) => (
          <Fragment key={i}>
            {node}
            {i < crumbsMobile.length - 1 && (
              <span className='mx-2 shrink-0'>/</span>
            )}
          </Fragment>
        ))}
      </div>
    );
  }

  // ===== DESKTOP =====
  if (isDesktop) {
    return (
      <div className='line-clamp-2 md:line-clamp-1 leading-7 text-caption-1'>
        <Link href='/' className='text-danger-500'>
          Home
        </Link>
        <span className='mx-2'>/</span>
        {breadcrumbs.map((category, index) => (
          <Fragment key={index}>
            <Link
              href={createSlug(
                '/shop/category/',
                category.name,
                category.id.toString()
              )}
              className='text-danger-500'
            >
              {category.name}
            </Link>
            <span className='mx-2'>/</span>
          </Fragment>
        ))}
        <span>{name}</span>
      </div>
    );
  }

  return (
    <div className='line-clamp-2 md:line-clamp-1 leading-7 text-caption-1'>
      <Link href='/' className='text-danger-500'>
        Home
      </Link>
      <span className='mx-2'>/</span>
      {breadcrumbs.map((category, index) => (
        <Fragment key={index}>
          <Link
            href={createSlug(
              '/shop/category/',
              category.name,
              category.id.toString()
            )}
            className='text-danger-500'
          >
            {category.name}
          </Link>
          <span className='mx-2'>/</span>
        </Fragment>
      ))}
      <span>{name}</span>
    </div>
  );
};

export default Breadcrumb;
