import { Sort, ArrowDown2 } from 'iconsax-react'
import { FC, useState, useEffect, useRef } from 'react'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'
import { ProductsResponse } from '@/types/products.types'

const sortOptions = [
    { key: '1', label: 'مرتبط ترین' },
    { key: '2', label: 'پربازدیدترین' },
    { key: '3', label: 'جدیدترین' },
    { key: '4', label: 'پرفروش ترین' },
    { key: '5', label: 'ارزانترین' },
    { key: '6', label: 'گرانترین' },
    { key: '7', label: 'پیشنهاد خریداران' },
]

type SortsProps = {
    data?: ProductsResponse
}

const Sorts: FC<SortsProps> = ({ data }) => {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()
    const [selectedSort, setSelectedSort] = useState('3') // default to newest
    const [showDropdown, setShowDropdown] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)

    const selectedOption = sortOptions.find(option => option.key === selectedSort)

    // خواندن sort از URL
    useEffect(() => {
        const sortFromUrl = searchParams.get('sort')
        if (sortFromUrl) {
            setSelectedSort(sortFromUrl)
        }
    }, [searchParams])

    const handleSortChange = (sortKey: string) => {
        setSelectedSort(sortKey)
        const params = new URLSearchParams(searchParams.toString())
        params.set('sort', sortKey)
        router.push(`${pathname}?${params.toString()}`)
    }

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setShowDropdown(false)
            }
        }

        if (showDropdown) {
            document.addEventListener('mousedown', handleClickOutside)
        }

        return () => {
            document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [showDropdown])

    return (
        <div className='flex justify-between items-center text-[#999999] text-sm border-b border-border pb-5'>
            {/* Desktop Version */}
            <div className='hidden lg:flex items-center gap-4'>
                <div className='flex gap-2 items-center'>
                    <Sort size={24} color='#333333' />
                    <div className='text-sm text-[#333333]'>مرتب سازی:</div>
                </div>

                {sortOptions.map((option) => (
                    <div
                        key={option.key}
                        className={`cursor-pointer ${selectedSort === option.key ? 'text-primary' : ''}`}
                        onClick={() => handleSortChange(option.key)}
                    >
                        {option.label}
                    </div>
                ))}
            </div>

            {/* Mobile Version */}
            <div className='lg:hidden flex items-center gap-2 relative' ref={dropdownRef}>
                <Sort size={20} color='#333333' />
                <div className='text-sm text-[#333333]'>مرتب سازی:</div>
                <div
                    className='flex items-center gap-1 cursor-pointer bg-gray-50 px-3 py-1.5 rounded-lg'
                    onClick={() => setShowDropdown(!showDropdown)}
                >
                    <span className='text-sm text-[#333333]'>{selectedOption?.label}</span>
                    <ArrowDown2 size={16} color='#333333' />
                </div>

                {showDropdown && (
                    <div className='absolute top-full right-0 mt-2 bg-white border border-border rounded-lg shadow-lg z-10 min-w-[180px]'>
                        {sortOptions.map((option) => (
                            <div
                                key={option.key}
                                className={`px-4 py-3 cursor-pointer text-sm hover:bg-gray-50 ${selectedSort === option.key ? 'text-primary bg-primary/10' : 'text-[#333333]'
                                    }`}
                                onClick={() => {
                                    handleSortChange(option.key)
                                    setShowDropdown(false)
                                }}
                            >
                                {option.label}
                            </div>
                        ))}
                    </div>
                )}
            </div>

            <div className='text-sm'>
                {data?.results?.pager?.totalItems || 0} کالا
            </div>
        </div>
    )
}

export default Sorts