import { ChangeEvent, useRef, useState } from 'react'
import cx from 'classnames'

import Icon from '@/components/shared/Icon'

type Props = {
  label: string
  options: {
    label: string
    value: string
  }[]
  selectedOption?: string
  onChange: (value: string) => void
}

export default function Filter({ label, options, selectedOption, onChange }: Props) {
  const selectRef = useRef<HTMLSelectElement>(null)

  return (
    <div className="relative">
      <div className="flex w-full sm:w-auto" aria-hidden>
        <p className="pr-4 text-subtitle" onClick={() => selectRef.current?.focus()}>
          {selectedOption ? options.find(option => option.value === selectedOption)?.label : `All ${label}`}
        </p>
        <Icon name="arrow-down" className="w-6 flex-shrink-0 ml-auto" />
      </div>

      <label className="absolute inset-0 opacity-0">
        <select
          ref={selectRef}
          value={selectedOption || ''}
          onChange={(e: ChangeEvent<HTMLSelectElement>) => onChange(e.target.value)}
          className="absolute inset-0 cursor-pointer"
        >
          <option value="">All {label}</option>
          {options.map(({ value, label }) => (
            <option key={value} value={value}>
              {label}
            </option>
          ))}
        </select>
        <span>Filter by {label}</span>
      </label>
    </div>
  )
}

export const CustomSelectFilter = ({ label, options, selectedOption, onChange }: Props) => {
  const [selectedValue, setSelectedValue] = useState<any>({
    selected: 'Select',
    value: '',
    isActive: false,
    isValid: false,
  })
  const { isActive } = selectedValue
  const hasValue = selectedValue.value !== ''

  const toggleSelect = (e: any) => {
    e.preventDefault()
    setSelectedValue((prevState: any) => ({
      ...prevState,
      isActive: !isActive,
    }))
  }

  const handleChangeValue = (e: any, value: any, label: any) => {
    e.preventDefault()
    onChange(value)
    setSelectedValue({ selected: label, isActive: false, isValid: true })
  }

  return (
    <div>
      <label
        id={label}
        htmlFor={label}
        className={cx(
          'block text-label mb-3 origin-[0_0] transition duration-100 delay-75 ease-[cubic-bezier(0,0.25,0.5,1)] sr-only',
          { 'scale-75': isActive || hasValue }
        )}
      >
        <span>Filter by {label}</span>
      </label>
      <div
        className={cx('w-full relative', {
          isActive: 'active',
        })}
      >
        <button
          role="button"
          className="flex justify-between items-start w-full min-h-[50px] text-subtitle text-left"
          onClick={e => toggleSelect(e)}
          tabIndex={0}
          aria-labelledby={label}
        >
          <span className="pr-4">
            {selectedOption ? options.find(option => option.value === selectedOption)?.label : `All ${label}`}
          </span>
          <Icon
            name="arrow-down"
            className={cx('w-[24px] h-[24px] text-black transition ease-in-out duration-150', {
              'rotate-180': isActive,
            })}
          />
        </button>
        <ul
          aria-expanded={isActive}
          role="listbox"
          className={cx('bg-white z-50', {
            block: isActive,
            hidden: !isActive,
          })}
        >
          {options.map(({ value, label }) => (
            <li key={value}>
              <button
                tabIndex={0}
                role="option"
                aria-selected={selectedValue.label == label}
                className="group block w-full py-[10px] text-[20px] leading-[30px] text-left"
                onClick={e => handleChangeValue(e, value, label)}
              >
                <span className="group-hover:border-b transition ease-in-out duration-150">{label}</span>
              </button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}
