'use client';
import { motion } from 'framer-motion';
import React from 'react';
import ProductCard from '@/widgets/products/ui/ProductCard';
import { useQuery } from '@tanstack/react-query';
import { getBestProduct } from '@/shared/config/api/testApi';
import { IProduct } from '@/shared/types/testApi';

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

const cardVariants = {
  hidden: { opacity: 0, y: 30 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.6, ease: [0, 0.55, 0.45, 1] as const },
  },
};

const HomeCheckout = () => {
  const { data: resProducts, isLoading: loadProducts } = useQuery({
    queryKey: ['best-products'],
    queryFn: () => getBestProduct({ popular: true }),
  });
  const productData: IProduct[] | undefined = resProducts?.results;

  if (loadProducts)
    return (
      <div className="bg-gray-50">
        <div className="custom-container min-h-[400px] flex justify-center items-center text-muted font-medium">
          Загрузка...
        </div>
      </div>
    );

  return (
    <div className="relative my-[50px]">
      <div className="relative z-10 custom-container">
        <motion.div
          initial={{ opacity: 0, top: '-20px' }}
          whileInView={{ opacity: 1, top: 0 }}
          transition={{ duration: 0.5 }}
          viewport={{ amount: 0.1, once: true }}
          className="relative"
        >
          <p className="text-center font-extrabold text-primary font-caveat text-[24px]">
            Популярные товары
          </p>
          <h4 className="text-center font-extrabold text-[32px] text-accent tracking-tighter">
            Горячие предложения дня — покупайте сейчас
          </h4>
        </motion.div>

        <motion.div
          variants={containerVariants}
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true, amount: 0.1 }}
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6 py-[20px]"
        >
          {productData &&
            productData.length > 0 &&
            productData?.map((item) => (
              <motion.div key={item.id} variants={cardVariants}>
                <ProductCard item={item} />
              </motion.div>
            ))}
        </motion.div>
      </div>
    </div>
  );
};

export default HomeCheckout;
