
"use client"

import { FC, useMemo, useState, useEffect } from 'react'
import { Setting5 } from 'iconsax-react'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import Input from '@/components/Input'
import { Button } from '@/components/ui/button'
import { useQuery } from '@tanstack/react-query'
import { getCategories } from '@/share/service/ShareService'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import CategoryTree from './CategoryTree'
import { Category } from '@/share/types/SharedTypes'

const Filters: FC = () => {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()

    const [selectedCategories, setSelectedCategories] = useState<string[]>([])
    const [minPrice, setMinPrice] = useState<string>('')
    const [maxPrice, setMaxPrice] = useState<string>('')
    const [inStockOnly, setInStockOnly] = useState<boolean>(false)
    const [rating, setRating] = useState<number | null>(null)

    const { data: categoriesData } = useQuery({
        queryKey: ['categories'],
        queryFn: getCategories,
        staleTime: 1000 * 60 * 10,
    })

    const categories: Category[] = useMemo(() => {
        return categoriesData?.results?.data ?? []
    }, [categoriesData])

    useEffect(() => {
        const qsCategories = searchParams.get('category')?.split(',').filter(Boolean) ?? []
        const qsMin = searchParams.get('minPrice') ?? ''
        const qsMax = searchParams.get('maxPrice') ?? ''
        const qsStock = searchParams.get('inStock') === '1'
        const qsRating = searchParams.get('rating')

        setSelectedCategories(qsCategories)
        setMinPrice(qsMin)
        setMaxPrice(qsMax)
        setInStockOnly(qsStock)
        setRating(qsRating ? Number(qsRating) : null)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const applyFilters = () => {
        const params = new URLSearchParams(searchParams.toString())
        if (selectedCategories.length > 0) {
            params.set('category', selectedCategories.join(','))
        } else {
            params.delete('category')
        }
        if (minPrice) params.set('minPrice', minPrice)
        else params.delete('minPrice')
        if (maxPrice) params.set('maxPrice', maxPrice)
        else params.delete('maxPrice')
        if (inStockOnly) params.set('inStock', '1')
        else params.delete('inStock')
        if (rating) params.set('rating', String(rating))
        else params.delete('rating')
        router.push(`${pathname}?${params.toString()}`)
    }

    const clearFilters = () => {
        setSelectedCategories([])
        setMinPrice('')
        setMaxPrice('')
        setInStockOnly(false)
        setRating(null)
        const params = new URLSearchParams(searchParams.toString())
            ;['category', 'minPrice', 'maxPrice', 'inStock', 'rating'].forEach((k) => params.delete(k))
        router.push(`${pathname}?${params.toString()}`)
    }

    return (
        <div className='w-[270px] border border-border rounded-[10px] p-5'>
            <div className='flex items-center gap-2.5'>
                <Setting5 size={24} color='#666666' />
                <div className='text-[#666666]'>فیلترها</div>
            </div>

            <div className='mt-3.5'>
                <Accordion type='multiple' className='w-full'>
                    <AccordionItem value='category'>
                        <AccordionTrigger className='text-[#333333]'>دسته‌بندی ها</AccordionTrigger>
                        <AccordionContent>
                            <CategoryTree
                                categories={categories}
                                selectedId={selectedCategories[0] ?? null}
                                onSelect={(id) => setSelectedCategories(id ? [id] : [])}
                            />
                        </AccordionContent>
                    </AccordionItem>

                    <AccordionItem value='price'>
                        <AccordionTrigger className='text-[#333333]'>قیمت</AccordionTrigger>
                        <AccordionContent>
                            <div className='grid grid-cols-2 gap-2.5'>
                                <Input
                                    label='حداقل'
                                    value={minPrice}
                                    onChange={(e) => setMinPrice(e.target.value)}
                                    placeholder='0'
                                    seprator
                                    inputMode='numeric'
                                />
                                <Input
                                    label='حداکثر'
                                    value={maxPrice}
                                    onChange={(e) => setMaxPrice(e.target.value)}
                                    placeholder='0'
                                    seprator
                                    inputMode='numeric'
                                />
                            </div>
                        </AccordionContent>
                    </AccordionItem>

                    <AccordionItem value='status'>
                        <AccordionTrigger className='text-[#333333]'>وضعیت موجودی</AccordionTrigger>
                        <AccordionContent>
                            <label className='flex items-center gap-2.5 text-sm text-[#4A4A4A]'>
                                <input
                                    type='checkbox'
                                    className='size-4 rounded border-border'
                                    checked={inStockOnly}
                                    onChange={(e) => setInStockOnly(e.target.checked)}
                                />
                                فقط کالاهای موجود
                            </label>
                        </AccordionContent>
                    </AccordionItem>

                    <AccordionItem value='rating'>
                        <AccordionTrigger className='text-[#333333]'>امتیاز خریداران</AccordionTrigger>
                        <AccordionContent>
                            <div className='flex flex-col gap-2.5 text-sm text-[#4A4A4A]'>
                                {[4, 3, 2].map((r) => (
                                    <label key={r} className='flex items-center gap-2.5'>
                                        <input
                                            type='radio'
                                            name='rating'
                                            className='size-4 border-border'
                                            checked={rating === r}
                                            onChange={() => setRating(r)}
                                        />
                                        {r} ستاره و بالاتر
                                    </label>
                                ))}
                                <button
                                    type='button'
                                    onClick={() => setRating(null)}
                                    className='text-xs text-muted-foreground hover:text-foreground text-right mt-1'
                                >
                                    حذف امتیاز
                                </button>
                            </div>
                        </AccordionContent>
                    </AccordionItem>
                </Accordion>
            </div>

            <div className='mt-4 grid grid-cols-2 gap-2.5'>
                <Button variant='outline' onClick={clearFilters}>حذف</Button>
                <Button onClick={applyFilters}>اعمال</Button>
            </div>
        </div>
    )
}

export default Filters