'use client';
import useFilterStore from '@/shared/store/filterStore';
import ProductCard from './ProductCard';
import Pagination from './Pagination';
import { IProduct } from '@/shared/types/testApi';
import { motion, AnimatePresence } from 'framer-motion';

type Props = {
  loading: boolean;
  products: IProduct[];
  totalPages: number;
};

const containerVariants = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.1,
    },
  },
};

const cardVariants = {
  hidden: { opacity: 0, y: 30 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.4 },
  },
};

const ProductList = ({ products, totalPages, loading }: Props) => {
  const { currentPage, setCurrentPage, categoryId, searchQuery } =
    useFilterStore();
  const filtered = products.filter((product) => {
    const matchCategory = categoryId
      ? product.category.id === categoryId
      : true;
    const matchSearch =
      product.title?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      product.subtitle?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      product.description?.toLowerCase().includes(searchQuery.toLowerCase());
    return matchCategory && matchSearch;
  });

  return (
    <div className="flex-1 flex flex-col justify-between">
      {loading ? (
        <div className="custom-container min-h-[400px] flex justify-center items-center text-muted">
          Загрузка...
        </div>
      ) : (
        <motion.div
          key={`${currentPage}-${categoryId}-${searchQuery}`}
          variants={containerVariants}
          initial="hidden"
          animate="visible"
          className="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2 lg:gap-3"
        >
          <AnimatePresence>
            {filtered.map((item) => (
              <motion.div
                key={item.id}
                variants={cardVariants}
                exit={{ opacity: 0 }}
              >
                <ProductCard item={item} />
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>
      )}

      <div className="mt-6">
        {totalPages > 1 && (
          <Pagination
            totalPages={totalPages}
            currentPage={currentPage}
            onChange={setCurrentPage}
          />
        )}
      </div>
    </div>
  );
};

export default ProductList;
