'use client'
import { FC, useState, useRef, useEffect } from 'react'
import { ArrowDown2 } from 'iconsax-react'
import { cn } from '@/lib/utils'

type SelectItem = {
    label: string
    value: string
}

type Props = {
    placeholder?: string
    items?: SelectItem[]
    value?: string
    name?: string
    onChange?: (e: { target: { name: string; value: string } }) => void
    className?: string
    error_text?: string
    disabled?: boolean
}

const Select: FC<Props> = ({
    placeholder,
    items = [],
    value,
    name,
    onChange,
    className,
    error_text,
    disabled = false
}) => {
    const [isOpen, setIsOpen] = useState(false)
    const [selectedItem, setSelectedItem] = useState<SelectItem | null>(
        items.find(item => item.value === value) || null
    )
    const dropdownRef = useRef<HTMLDivElement>(null)

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

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

    useEffect(() => {
        const item = items.find(item => item.value === value)
        setSelectedItem(item || null)
    }, [value, items])

    const handleSelect = (item: SelectItem) => {
        setSelectedItem(item)
        setIsOpen(false)

        if (onChange && name) {
            onChange({
                target: {
                    name,
                    value: item.value
                }
            })
        }
    }

    return (
        <div className="w-full relative" ref={dropdownRef}>
            <div
                className={cn(
                    "w-full h-10 sm:h-12 px-3 sm:px-4 py-2 text-xs sm:text-sm border border-[#D0D0D0] rounded-xl bg-white cursor-pointer flex items-center justify-between",
                    disabled && "bg-gray-100 cursor-not-allowed",
                    error_text && "border-red-500",
                    className
                )}
                onClick={() => !disabled && setIsOpen(!isOpen)}
            >
                <span className={selectedItem ? "text-black" : "text-gray-500"}>
                    {selectedItem ? selectedItem.label : placeholder}
                </span>
                <ArrowDown2
                    size={16}
                    className={cn(
                        "transition-transform duration-200",
                        isOpen && "rotate-180"
                    )}
                />
            </div>

            {isOpen && (
                <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-[#D0D0D0] rounded-xl shadow-lg z-50 max-h-48 sm:max-h-60 overflow-y-auto">
                    {items.map((item, index) => (
                        <div
                            key={index}
                            className="px-3 sm:px-4 py-2 hover:bg-gray-50 cursor-pointer text-xs sm:text-sm"
                            onClick={() => handleSelect(item)}
                        >
                            {item.label}
                        </div>
                    ))}
                </div>
            )}

            {error_text && (
                <div className="text-xs text-red-500 mt-1">
                    {error_text}
                </div>
            )}
        </div>
    )
}

export default Select
