'use client'

import type { IComboboxState } from './types'
import { PktIcon } from '../icon/Icon'

interface IListboxProps {
  state: IComboboxState
}

export const Listbox = ({ state }: IListboxProps) => {
  const {
    listboxId,
    label,
    isOpen,
    options,
    filteredOptions,
    multiple,
    disabled,
    maxIsReached,
    maxlength,
    includeSearch,
    allowUserInput,
    addValueText,
    userInfoMessage,
    searchPlaceholder,
    searchValue,
    handleOptionClick,
    handleOptionKeydown,
    handleSearchInput,
    handleSearchKeydown,
    handleNewOptionClick,
    handleNewOptionKeydown,
    listboxRef,
  } = state

  const selectedCount = filteredOptions.filter((opt) => opt.selected).length
  const showMaxBanner = multiple && selectedCount > 0 && maxlength != null && maxlength > 0
  const showNewOptionBanner = allowUserInput && addValueText && !maxIsReached
  const showUserMessage = !!userInfoMessage

  const listboxClasses = ['pkt-listbox', isOpen && 'pkt-listbox__open', 'pkt-txt-16-light'].filter(Boolean).join(' ')

  return (
    <>
      <div
        ref={listboxRef}
        id={listboxId}
        className={listboxClasses}
        role={filteredOptions.length > 0 ? 'listbox' : undefined}
        aria-label={filteredOptions.length > 0 ? `Liste: ${label || ''}` : undefined}
        aria-multiselectable={filteredOptions.length > 0 && multiple ? 'true' : undefined}
      >
        <div className="pkt-listbox__banners">
          {includeSearch && (
            <div className="pkt-listbox__search">
              <span className="pkt-listbox__search-icon">
                <PktIcon name="magnifying-glass-small" />
              </span>
              <input
                className="pkt-txt-16-light"
                type="text"
                aria-label="Søk i listen"
                form=""
                placeholder={searchPlaceholder || 'Søk...'}
                onChange={handleSearchInput}
                onKeyDown={handleSearchKeydown}
                value={searchValue}
                data-type="searchbox"
                disabled={disabled}
                readOnly={disabled}
                role="searchbox"
              />
            </div>
          )}
          {showMaxBanner && (
            <div className="pkt-listbox__banner pkt-listbox__banner--maximum-reached">
              {selectedCount} av maks {maxlength} mulige er valgt.
            </div>
          )}

          {showUserMessage && (
            <div className="pkt-listbox__banner pkt-listbox__banner--user-message">
              <PktIcon className="pkt-listbox__banner-icon" name="exclamation-mark-circle" />
              {userInfoMessage}
            </div>
          )}

          {showNewOptionBanner && (
            <div
              className="pkt-listbox__banner pkt-listbox__banner--new-option pkt-listbox__option"
              data-type="new-option"
              data-value={addValueText}
              data-selected="false"
              tabIndex={0}
              onClick={() => handleNewOptionClick(addValueText)}
              onKeyDown={handleNewOptionKeydown}
            >
              <PktIcon className="pkt-listbox__banner-icon" name="plus-sign" />
              Legg til &quot;{addValueText}&quot;
            </div>
          )}

          {options.length === 0 && filteredOptions.length === 0 && !showUserMessage && (
            <div className="pkt-listbox__banner pkt-listbox__banner--empty">
              <PktIcon className="pkt-listbox__banner-icon" name="exclamation-mark-circle" />
              Tom liste
            </div>
          )}
        </div>

        <ul className="pkt-listbox__options" role="presentation">
          {filteredOptions.map((option, index) => {
            const optionClasses = [
              'pkt-listbox__option',
              !multiple && option.selected && 'pkt-listbox__option--selected',
              multiple && 'pkt-listbox__option--checkBox',
            ]
              .filter(Boolean)
              .join(' ')

            const isOptionDisabled = disabled || option.disabled || (maxIsReached && !option.selected)

            return (
              <li
                key={`${option.value}-${index}`}
                className={optionClasses}
                onClick={() => handleOptionClick(option.value)}
                onKeyDown={(e) => handleOptionKeydown(e, option.value)}
                aria-selected={option.selected ? 'true' : 'false'}
                tabIndex={isOptionDisabled ? -1 : 0}
                data-index={index}
                data-value={option.value}
                data-selected={option.selected ? 'true' : 'false'}
                data-disabled={isOptionDisabled || undefined}
                aria-disabled={isOptionDisabled ? 'true' : 'false'}
                role="option"
                id={`${listboxId}-${index}`}
              >
                {multiple ? (
                  <input
                    className="pkt-input-check__input-checkbox"
                    type="checkbox"
                    tabIndex={-1}
                    value={option.value}
                    checked={option.selected || false}
                    readOnly
                    aria-hidden="true"
                    disabled={isOptionDisabled}
                  />
                ) : option.selected ? (
                  <PktIcon name="check-big" />
                ) : null}

                <span className="pkt-listbox__option-label" id={`${listboxId}-option-label-${index}`}>
                  {option.prefix && <span className="pkt-listbox__option-prefix">{option.prefix}</span>}
                  {option.label || option.value}
                </span>

                {option.description && (
                  <span className="pkt-listbox__option-description pkt-txt-14-light">{option.description}</span>
                )}
              </li>
            )
          })}
        </ul>
      </div>
      <div aria-live="polite" className="pkt-visually-hidden">
        {userInfoMessage}
      </div>
    </>
  )
}
