"use client"

import React from 'react'
import { P } from '@/components/ui/typography'
import { useRouter, useSearchParams } from 'next/navigation'
import { useLocale } from 'next-intl'
import glossaryData from '@/utils/dadycar_glossary_final_152_terms.json'

interface Props {
    item: {
        label_en: string
        label_fr: string
    }
}

const GlossaireCategory: React.FC<Props> = ({ item }) => {
    const router = useRouter()
    const searchParams = useSearchParams()
    const locale = useLocale()

    const currentCategory = searchParams.get('category')
    const search = searchParams.get('search')
    const innovation = searchParams.get('innovation')
    const letter = searchParams.get('letter')

    const categoryLabel = locale === "en" ? item?.label_en : item?.label_fr

    const handleCategory = () => {
        const params = new URLSearchParams(searchParams.toString())
        
        // Toggle category
        if (currentCategory === categoryLabel) {
            params.delete("category")
        } else {
            params.set("category", categoryLabel)
        }
        
        const basePath = locale === "en" ? "/en/glossary" : "/glossaire"
        router.push(`${basePath}?${params.toString()}`, { scroll: false })
    }

    // Calculate count for this specific category
    const categoryCount = glossaryData?.glossary?.terms?.filter((term) =>
        (locale === "en" ? term?.category_en === categoryLabel : term?.category_fr === categoryLabel)
        && (search ? 
            (locale === "en" 
                ? term?.name_en?.toLowerCase()?.includes(search?.toLowerCase()) 
                : term?.name_fr?.toLowerCase()?.includes(search?.toLowerCase())
            ) : true
        )
        && (innovation ? term?.innovation === true : true)
        && (letter ? 
            (locale === "en" 
                ? term?.name_en?.toUpperCase().startsWith(letter.toUpperCase()) 
                : term?.name_fr?.toUpperCase().startsWith(letter.toUpperCase())
            ) : true
        )
    )?.length || 0

    const isActive = currentCategory === categoryLabel

    return (
        <div 
            className={`w-full group px-[17px] py-[13px] rounded-[8px] flex items-center justify-between cursor-pointer glossary-category-item ${isActive && "glossary-category-item-active"}`} 
            onClick={handleCategory}
        >
            <div className='flex items-center gap-2 flex-1'>
                <P className='!text-[16px] !font-[400] text-[#27272A]'>{categoryLabel}</P>
            </div>
            <div className={`w-[28px] h-[28px] rounded-full flex items-center justify-center ${isActive ? "bg-[#52A5EF]" : "bg-[#64748B]"} group-hover:bg-[#52A5EF]`}>
                <P className='!text-[12px] !font-[500] text-white'>{categoryCount}</P>
            </div>
        </div>
    )
}

export default GlossaireCategory