import React from 'react';

import { ControlProps, PropEnum } from '../../../@types/settings.js';

import './CtrlEnumInline.scss';

interface CtrlEnumInlineProps extends ControlProps {
  prop: PropEnum;
}

export default function CtrlEnumInline({
  currMod,
  updatePath,
  prop,
  value,
  inheritVal,
  deleteProp,
  updateProps,
}: CtrlEnumInlineProps) {
  if (!prop.options) {
    return <div>Missing options for enum-inline</div>;
  }

  const indexOfValue =
    prop.options.length && typeof prop.options[0] === 'object'
      ? prop.options.findIndex((option: any) => option.value === value)
      : prop.options.indexOf(value);

  return (
    <React.Fragment key={currMod.id + updatePath}>
      {prop.clearable !== false && value && !inheritVal && (
        <div
          className='ctrl-enum-inline__clear-btn'
          onClick={() => deleteProp(updatePath)}
        >
          Clear
        </div>
      )}
      <div className='ctrl-enum-inline__options-container'>
        {prop.options.map((option: any) => (
          <div
            key={option?.value ?? option}
            onClick={() => {
              updateProps(currMod.id, updatePath, option?.value ?? option);
            }}
            className={`ctrl-enum-inline__options-container__option ${
              value === (option?.value ?? option)
                ? inheritVal
                  ? 'ctrl-enum-inline__options-container__option--active-inherit-val'
                  : 'ctrl-enum-inline__options-container__option--active'
                : 'ctrl-enum-inline__options-container__option--inactive'
            }`}
          >
            {option?.label ?? option}
          </div>
        ))}
        {prop.allowOther && (
          <div
            onClick={() => {
              updateProps(currMod.id, updatePath, 'other');
            }}
            className={`ctrl-enum-inline__options-container__option-other ${
              indexOfValue > -1
                ? 'ctrl-enum-inline__options-container__option-other--inactive'
                : inheritVal
                ? 'ctrl-enum-inline__options-container__option-other--active-inherit-val'
                : 'ctrl-enum-inline__options-container__option-other--active'
            }`}
          >
            Other
          </div>
        )}
      </div>
      {prop.allowOther &&
        prop.options
          .map((opt) => (typeof opt === 'object' ? opt.value : opt))
          .indexOf(value) === -1 && (
          <input
            key={currMod.id + updatePath}
            className={`ctrl-enum-inline__other-input-field`}
            type='text'
            placeholder={inheritVal ? value : ''}
            value={inheritVal ? '' : value}
            onChange={(e) =>
              updateProps(currMod.id, updatePath, e.target.value)
            }
          />
        )}
    </React.Fragment>
  );
}
