'use client';
import useFilterStore from '@/shared/store/filterStore';
import { ICategory } from '@/shared/types/testApi';
import React from 'react';

interface ICategoresProps {
  categories: ICategory[];
}

const Categories = ({ categories }: ICategoresProps) => {
  const { categoryId, setCategoryId, setCurrentPage, setSearchQuery } =
    useFilterStore();

  const handleSelectCategory = (id: number | null) => {
    setCategoryId(id);
    setCurrentPage(1);
    setSearchQuery('');
  };

  const totalCount =
    categories &&
    categories.reduce((acc, item) => acc + (item?.product_count || 0), 0);

  return (
    <div className="bg-muted-foreground rounded-sm py-[15px] space-y-2">
      <div className="font-bold text-accent px-[20px]">Категории</div>
      <div className="px-[10px]">
        <div
          onClick={() => handleSelectCategory(null)}
          className={`flex justify-between cursor-pointer hover:bg-white duration-100 items-center gap-1 text-[14px] py-[7px] px-[10px] rounded-sm border-b
            ${!categoryId ? 'text-primary font-bold bg-white' : 'text-muted font-medium hover:text-primary'}
          `}
        >
          <div>Все продукты</div>
          <div className="text-accent text-[13px]">({totalCount})</div>
        </div>

        {categories.map((item) => (
          <div
            key={item.id}
            onClick={() => handleSelectCategory(item.id)}
            className={`flex justify-between cursor-pointer hover:bg-white duration-100 items-center gap-1 text-[14px] py-[7px] px-[10px] rounded-sm border-b
              ${categoryId === item.id ? 'text-primary font-bold bg-white' : 'text-muted font-medium hover:text-primary'}
            `}
          >
            <div>{item.title}</div>
            <div className="text-accent text-[13px] text-nowrap">
              ({item?.product_count || 0})
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Categories;
