import { type FC, useState, useRef, useEffect } from 'react'
import { ArrowDown2 } from 'iconsax-react'
import { clx } from '../helpers/utils'
import { Checkbox } from './ui/checkbox'
import type { ItemsSelectType } from './Select'

type MultiSelectProps = {
    className?: string
    items: ItemsSelectType[]
    placeholder?: string
    label?: string
    value?: string[]
    onChange?: (values: string[]) => void
    error_text?: string
}

const MultiSelect: FC<MultiSelectProps> = ({
    className,
    items,
    placeholder,
    label,
    value = [],
    onChange,
    error_text,
}) => {
    const [isOpen, setIsOpen] = useState(false)
    const containerRef = useRef<HTMLDivElement>(null)

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

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

    const handleToggle = (itemValue: string) => {
        const newValues = value.includes(itemValue)
            ? value.filter((v) => v !== itemValue)
            : [...value, itemValue]
        onChange?.(newValues)
    }

    const displayText =
        value.length === 0
            ? placeholder || 'انتخاب کنید'
            : value.length === 1
                ? items.find((item) => item.value === value[0])?.label || placeholder
                : `${value.length} مورد انتخاب شده`

    return (
        <div className="w-full min-w-[180px] relative" ref={containerRef}>
            {label && <label className="text-sm">{label}</label>}
            <button
                type="button"
                onClick={() => setIsOpen(!isOpen)}
                className={clx(
                    'w-full text-black whitespace-nowrap border appearance-none border-border !bg-white px-2.5 h-10 text-sm rounded-[10px] bg-gray text-right flex items-center justify-between',
                    className,
                    label && 'mt-1',
                    isOpen && 'border-primary'
                )}
            >
                <span className="whitespace-nowrap">{displayText}</span>
                <ArrowDown2
                    size={16}
                    color="black"
                    className={clx('transition-transform', isOpen && 'rotate-180')}
                />
            </button>

            {isOpen && (
                <div className="absolute z-50 w-full mt-1 bg-white border border-border rounded-[10px] shadow-lg max-h-60 overflow-y-auto">
                    {items.map((item) => {
                        const isChecked = value.includes(item.value)
                        return (
                            <div
                                key={item.value}
                                className="flex items-center gap-2 px-3 py-2 hover:bg-secondary cursor-pointer"
                                onClick={() => handleToggle(item.value)}
                            >
                                <Checkbox checked={isChecked} />
                                <span className="text-sm text-foreground whitespace-nowrap">
                                    {item.label}
                                </span>
                            </div>
                        )
                    })}
                </div>
            )}

            {error_text && error_text !== '' && (
                <div className="text-sm text-destructive mt-1">{error_text}</div>
            )}
        </div>
    )
}

export default MultiSelect

