'use client';
import React from 'react';
import SearchProduct from './SearchProduct';
import useFilterStore from '@/shared/store/filterStore';
import { useQuery } from '@tanstack/react-query';
import { getCategory, getProduct } from '@/shared/config/api/testApi';
import ProductList from './ProductList';
import Categories from './CategoriesList';

const ProductsCategory = () => {
  const { currentPage, categoryId, searchQuery } = useFilterStore();
  const {
    data: resCategories,
    isLoading: loadCategory,
    isError: errorCategory,
  } = useQuery({
    queryKey: ['categories'],
    queryFn: () => getCategory(),
  });

  const {
    data: resProducts,
    isLoading: loadProducts,
    isError: errorProducts,
  } = useQuery({
    queryKey: ['products', currentPage, categoryId, searchQuery],
    queryFn: () =>
      getProduct(
        searchQuery.length > 0
          ? { search: searchQuery }
          : { page: currentPage, category: categoryId || undefined },
      ),
  });

  if (loadCategory) {
    return (
      <div className="custom-container min-h-[400px] flex justify-center items-center text-muted">
        Загрузка...
      </div>
    );
  }

  if (errorCategory || errorProducts) {
    return (
      <div className="custom-container min-h-[300px] flex flex-col items-center justify-center text-red-500 space-y-4 text-center">
        <div className="text-xl font-semibold text-accent">
          Произошла ошибка при загрузке данных
        </div>
        <div className="text-muted text-sm max-w-[400px]">
          Возможно, проблема с интернет-соединением или временная ошибка
          сервера. Пожалуйста, попробуйте перезагрузить страницу.
        </div>
        <button
          onClick={() => window.location.reload()}
          className="px-4 py-2 bg-primary text-white font-medium text-[12px] cursor-pointer rounded-full transition"
        >
          Повторить загрузку
        </button>
      </div>
    );
  }

  const categories = resCategories?.results || [];
  const products = resProducts?.results || [];

  return (
    <div className="my-[30px]">
      <div className="custom-container">
        <div className="flex justify-between max-md:flex-col gap-3">
          <div className="min-w-[250px] md:max-w-[250px] space-y-4">
            <SearchProduct />
            <Categories categories={categories} />
          </div>
          <ProductList
            loading={loadProducts}
            products={products}
            totalPages={resProducts?.total_pages || 1}
          />
        </div>
      </div>
    </div>
  );
};

export default ProductsCategory;
