
"use client"

import { FC } from 'react'
import { Setting5 } from 'iconsax-react'
import { Button } from '@/components/ui/button'
import Modal from '@/components/Modal'
import { useFiltersData } from '../hooks/useFiltersData'
import FilterSection from './FilterSection'

interface FiltersProps {
    isMobile?: boolean
    isOpen?: boolean
    onClose?: () => void
    categoryUrl?: string
}

const Filters: FC<FiltersProps> = ({
    isMobile = false,
    isOpen = false,
    onClose,
    categoryUrl = 'Organic-supermarket'
}) => {
    const {
        filterState,
        categories,
        brands,
        isLoading,
        priceMinMaxRange,
        applyCategoryFilter,
        updatePriceRange,
        applyStockFilter,
        applyBrandFilter,
        clearBrandFilter,
        applyWholesaleFilter,
        clearAllFilters,
    } = useFiltersData({ categoryUrl })

    const handleClearFilters = () => {
        clearAllFilters()

        // Close mobile modal after clearing filters
        if (isMobile && onClose) {
            onClose()
        }
    }


    const FilterContent = () => (
        <>
            <div className='flex items-center gap-2.5'>
                <Setting5 size={24} color='#666666' />
                <div className='text-[#666666]'>فیلترها</div>
            </div>

            <FilterSection
                categories={categories}
                brands={brands}
                filterState={filterState}
                onCategoryChange={applyCategoryFilter}
                onPriceChange={updatePriceRange}
                onStockChange={applyStockFilter}
                onBrandChange={applyBrandFilter}
                onBrandClear={clearBrandFilter}
                onWholesaleChange={applyWholesaleFilter}
                categoryUrl={categoryUrl}
                priceMinMaxRange={priceMinMaxRange}
            />

            <div className='mt-4'>
                <Button
                    variant='outline'
                    onClick={handleClearFilters}
                    className='w-full'
                    disabled={isLoading}
                >
                    حذف همه فیلترها
                </Button>
            </div>
        </>
    )

    if (isMobile) {
        return (
            <Modal
                open={isOpen}
                close={onClose || (() => { })}
                title="فیلترها"
                isHeader={true}
            >
                <div className='max-h-[70vh] overflow-y-auto'>
                    <FilterContent />
                </div>
            </Modal>
        )
    }

    return (
        <div className='w-[270px] hidden lg:block border border-border rounded-[10px] p-5 h-fit'>
            <FilterContent />
        </div>
    )
}

export default Filters