'use client'
import { useEffect, useState } from 'react'

export default function QSelectBox({ title = '', options, onChange, value, disabled = false }) {
  const [openSelect, setOpenSelect] = useState(false)
  const [selected, setSelected] = useState(title === '' ? options[0].name : title)

  const handleClickSelectOption = (option) => {
    setSelected(option.name)
    onChange?.(option)
  }

  useEffect(() => {
    value && handleClickSelectOption(value)
  }, [value])

  return (
    <div className={`sort-select ${openSelect ? 'active' : ''}`} onClick={disabled ? () => {} : () => setOpenSelect(!openSelect)}>
      <p>{selected}</p>
      <ul className="select-item-wrap">
        {options?.map((option) => (
          <li key={option.id} className="select-item" onClick={() => handleClickSelectOption(option)}>
            <button key={option.id + 'btn'}>{option.name}</button>
          </li>
        ))}
      </ul>
    </div>
  )
}
