import React from "react"
import CreatableSelect from "react-select/creatable"

function RSelectCreatable({ options, value, onChange, placeholder = "Type and press Enter...", isMulti = true }) {
    return (
        <CreatableSelect
            isMulti={isMulti}
            options={options}
            value={
                isMulti
                    ? options.filter((opt) => value?.includes(opt.value))
                    : options.find((opt) => opt.value === value) || null
            }
            onChange={(selected) => {
                if (isMulti) {
                    onChange(selected ? selected.map((opt) => opt.value) : [])
                } else {
                    onChange(selected ? selected.value : null)
                }
            }}
            placeholder={placeholder}
            isSearchable
            isClearable
            className="w-full text-bodyTextSecondary"
            classNames={{
                control: ({ isFocused }) =>
                    `flex min-h-[42px] rounded-lg border shadow-sm text-sm transition 
                     ${isFocused ? "border-primary ring-2 ring-primary/40" : "border-gray-300 dark:border-gray-700"} 
                     bg-white dark:bg-zinc-900`,
                valueContainer: () => "px-2",
                placeholder: () => "text-bodyTextSecondary dark:text-gray-400",
                singleValue: () => "text-bodyTextSecondary dark:text-gray-100",
                indicatorsContainer: () => "px-2 gap-1",
                dropdownIndicator: ({ isFocused }) =>
                    `transition ${isFocused ? "text-gray-600 dark:text-gray-100" : "text-bodyTextSecondary dark:text-gray-300"}`,
                clearIndicator: () => "text-gray-500 hover:text-red-500 transition",
                menu: () =>
                    "mt-1 rounded-lg shadow-lg border border-gray-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 z-50",
                menuList: () => "p-0",
                option: ({ isFocused, isSelected }) =>
                    `px-3 py-2 text-sm cursor-pointer transition-colors 
                     ${isSelected ? "bg-primary text-bodyTextSecondary" : isFocused ? "bg-gray-100 dark:bg-gray-700" : "text-bodyTextSecondary dark:text-gray-100"}`,
                multiValue: () => "bg-gray-200 dark:bg-gray-700 rounded-md flex items-center px-1",
                multiValueLabel: () => "text-bodyTextSecondary dark:text-gray-100 text-sm",
                multiValueRemove: () => "text-gray-500 hover:text-red-500 cursor-pointer",
            }}
        />
    )
}

export { RSelectCreatable }
