'use client'

import React, { useEffect, useState } from 'react'
import Product from '../Product/Product'
import { ProductType } from '@/type/ProductType'
import { motion } from 'framer-motion'

interface Props {
    data: Array<ProductType>;
    category: Array<ProductType>;
}

const FeatureProduct: React.FC<Props> = ({ data, category }) => {

    const [activeTab, setActiveTab] = useState<string>('');
    useEffect(() => {
        if (category[0]?.name) {
            setActiveTab(category[0]?.name)
        }
    }, [category[0]?.name])

    const handleTabClick = (type: string) => {
        setActiveTab(type);
    };

    const filteredProducts = data.filter((product) => product.category === activeTab);
    return (
        <>
            <div className="what-new-block md:pt-20 pt-10">
                <div className="container">
                    <div className="heading flex flex-col items-center text-center">
                        <div className="heading3">What{String.raw`'s`} new</div>
                        <div className="menu-tab style-pet flex items-center gap-2 p-1 bg-surface rounded-2xl mt-6">
                            {category?.map((cat: any) => (
                                <div
                                    key={cat?.id}
                                    className={`tab-item relative text-secondary text-button-uppercase py-2 px-5 cursor-pointer duration-500 hover:text-black ${activeTab === cat?.name ? 'active' : ''}`}
                                    onClick={() => handleTabClick(cat?.name)}
                                >
                                    {activeTab === cat?.name && (
                                        <motion.div layoutId='active-pill' className='absolute inset-0 rounded-2xl bg-black'></motion.div>
                                    )}
                                    <span className='relative text-button-uppercase z-[1]'>
                                        {cat?.name}
                                    </span>
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="list-product hide-product-sold grid lg:grid-cols-4 grid-cols-2 sm:gap-[30px] gap-[20px] md:mt-10 mt-6">
                        {filteredProducts.slice(0, 4).map((prd, index) => (
                            <Product data={prd} type='grid' key={index} style='style-1' />
                        ))}
                    </div>
                </div>
            </div>
        </>
    )
}

export default FeatureProduct