'use client'

import React, { type ChangeEvent, type ReactElement, useEffect, useState } from 'react'
import Label from '@/Components/Inputs/Label'
import Description from '@/Components/Inputs/Description'
import { createButtonClass, makeClassName } from '@/utils'
import { type ISelectOptionProps, type ISelectProps } from '@/Types/InputTypes'
import { Select as ShadSelect, SelectContent as ShadSelectContent, SelectGroup as ShadSelectGroup, SelectItem as ShadSelectItem, SelectLabel as ShadSelectLabel, SelectTrigger as ShadSelectTrigger, SelectValue as ShadSelectValue } from '@/Components/ui/select'
import { SelectItem } from '@radix-ui/react-select'
import { Cross2Icon } from '@radix-ui/react-icons'
import Button from '@/Components/Buttons/Button'

function Option(option: ISelectOptionProps): ReactElement {
  return (
    <option value={option.value}>{option.label}</option>
  )
}

export default function Select({
  children,
  placeholder = 'Select one',
  includePrompt = true,
  onChange,
  onFocus,
  onBlur,
  value,
  id,
  testId = 'select',
  options = [],
  label,
  description,
  before,
  after,
  size = 'med',
  variant,
  defaultClassName = 'justify-between px-4',
  disabled = false,
  className = '',
  defaultWrapperClassName = 'block',
  wrapperClassName = '',
  error,
  clearable

}: ISelectProps): ReactElement {
  const [v, setV] = useState<string | number | undefined>(value)
  const updateValue = (newValue: string | number | undefined): void => {
    setV(newValue)
  }
  useEffect(() => {
    updateValue(value)
  }, [value])

  useEffect(() => {
    console.log('V UPDTEAD!', v)
  }, [v])

  const optionsToUse = options.slice()
  if (includePrompt && placeholder !== undefined) {
    optionsToUse.unshift({ label: placeholder, value: '' })
  }
  const optionsMap = Object.fromEntries(optionsToUse.map(o => [o.value, o]))
  const onSelectChange = (e: string | undefined): void => {
    const newV = e
    updateValue(newV)
    if (typeof onChange === 'function') {
      if (newV === undefined || newV === '' || optionsMap[newV] === undefined) {
        onChange(undefined)
      } else {
        onChange(optionsMap[newV])
      }
    }
  }

  const sizeToUse = size !== undefined ? size : 'md'
  const clearableToUse = clearable !== undefined ? clearable : placeholder !== undefined && placeholder !== ''

  return (
    <label className={makeClassName({
      defaultClassName: defaultWrapperClassName,
      className: wrapperClassName
    })}>
      {
        before !== undefined ? before : ''
      }
      {
        typeof label === 'string'
          ? <Label label={label} disabled={disabled} />
          : label !== undefined ? label : ''
      }
      {
        typeof description === 'string'
          ? <Description description={description} disabled={disabled} />
          : description !== undefined ? description : ''
      }
      <div className="flex gap-2">

        <ShadSelect onValueChange={onSelectChange} disabled={disabled} value={v !== undefined && v !== '' ? String(v) : ''}>
          <ShadSelectTrigger onFocus={onFocus} onBlur={onBlur} className={createButtonClass({
            size,
            variant,
            className: makeClassName({
              defaultClassName,
              className,
              error
            })
          })
          }>
            <ShadSelectValue placeholder={placeholder} />
          </ShadSelectTrigger>
          <ShadSelectContent>
            <ShadSelectGroup>
              {
                options.map(option => (
                  <ShadSelectItem key={option.value} value={String(option.value)}>{option.label}</ShadSelectItem>
                ))
              }
            </ShadSelectGroup>
          </ShadSelectContent>
          {
            clearableToUse && v !== undefined && v !== ''
              ? <Button size={size} variant={'none'} onClick={() => onSelectChange(undefined)}>
                <Cross2Icon className='font-bold' />
              </Button>
              : null
          }
        </ShadSelect>
        {
          after !== undefined ? after : ''
        }
      </div>
    </label>
  )
}
