'use client';

import { product_api } from '@/shared/config/api/product/api';
import { usePathname, useRouter } from '@/shared/config/i18n/navigation';
import { Card } from '@/shared/ui/card';
import { GlobalPagination } from '@/shared/ui/global-pagination';
import { Skeleton } from '@/shared/ui/skeleton';
import { ProductCard } from '@/widgets/categories/ui/product-card';
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, ShoppingBag } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useParams, useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';

const PAGE_SIZE = 36;

const Product = () => {
  const { subId } = useParams();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const t = useTranslations();

  const [page, setPage] = useState(1);

  useEffect(() => {
    const urlPage = Number(searchParams.get('page')) || 1;
    setPage(urlPage);
  }, [searchParams]);

  const {
    data: product,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['product_list', subId, page],
    queryFn: () => {
      if (!subId) throw new Error('Category ID is required');
      return product_api.list({
        page,
        page_size: PAGE_SIZE,
        product_type_id: Number(subId),
      });
    },
    select(data) {
      return data.data;
    },
    enabled: !!subId,
  });

  const activeProducts = useMemo(() => {
    return product?.results?.filter((item) => item.state === 'A') ?? [];
  }, [product]);

  const handleBack = () => {
    router.back();
  };

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('page', newPage.toString());

    router.push(`${pathname}?${params.toString()}`);
  };

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [page]);

  return (
    <div className="custom-container p-4 mb-5 flex flex-col min-h-[85vh]">
      <div className="flex-1">
        {/* Header */}
        <div className="mb-6">
          <button
            onClick={handleBack}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-4"
          >
            <ArrowLeft className="w-5 h-5" />
            <span>{t('Orqaga')}</span>
          </button>

          <p className="text-gray-600 text-sm">
            {product?.total ?? 0} {t('ta mahsulot')}
          </p>
        </div>

        {/* Products */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 gap-3">
          {/* Loading */}
          {isLoading &&
            Array.from({ length: 6 }).map((_, index) => (
              <Card key={index} className="p-3 space-y-3 rounded-xl">
                <Skeleton className="h-40 sm:h-48 md:h-56 w-full rounded-lg" />
                <Skeleton className="h-4 w-3/4" />
                <Skeleton className="h-4 w-1/2" />
                <Skeleton className="h-10 w-full rounded-lg" />
              </Card>
            ))}

          {/* Empty state */}
          {!isLoading && activeProducts.length === 0 && (
            <div className="col-span-full flex flex-col items-center justify-center py-24 text-gray-500">
              <div className="text-5xl mb-4">
                <ShoppingBag size={70} />
              </div>
              <p className="text-lg font-medium text-center">
                {t("Hozirchali bu kategoriyada mahsulot yo'q")}
              </p>
            </div>
          )}

          {/* Products list */}
          {!isLoading &&
            activeProducts.map((item) => (
              <ProductCard key={item.id} product={item} error={isError} />
            ))}
        </div>
      </div>

      {/* Pagination */}
      {product && product.total > PAGE_SIZE && (
        <div className="w-full mt-6 flex justify-end">
          <GlobalPagination
            page={page}
            total={product.total}
            pageSize={PAGE_SIZE}
            onChange={handlePageChange}
          />
        </div>
      )}
    </div>
  );
};

export default Product;
