import { BooleanField, SchemaFieldProps } from '@vev/utils';
import React from 'react';
import { SilkeBox } from '../../silke-box';
import { SilkeToggle } from '../../silke-toggle';
import { SilkeCheckbox } from '../../silke-checkbox';
import { SilkeTextFieldOutline } from '../../silke-text-field/silke-text-field-outline';
import { SilkeTextFieldItem } from '../../silke-text-field';
import { SilkeTextSmall } from '../../silke-text';
import { getTitle } from './utils/schema-util';

const Toggle = ({
  schema,
  value,
  disabled,
  readonly,
  onChange,
}: SchemaFieldProps<BooleanField>) => {
  const display = schema.options?.display || 'toggle';
  const title = getTitle(schema);
  const isCheckbox = display === 'checkbox';
  const toggle = () => !disabled && !readonly && onChange(!value);

  return (
    <SilkeBox flex>
      <SilkeTextFieldOutline
        label={title}
        size="s"
        flex
        disabled={disabled}
        tooltip={schema.description}
      >
        <SilkeBox
          tag="button"
          flex
          vAlign="center"
          hPad="s"
          cursor="pointer"
          onClick={toggle}
          data-input
          style={{ outline: 'none', background: 'none', border: 'none', textAlign: 'left' }}
          onKeyDown={(e: React.KeyboardEvent) => {
            if (e.key === ' ') { e.preventDefault(); toggle(); }
          }}
        >
          <SilkeTextSmall>{title}</SilkeTextSmall>
        </SilkeBox>
        <SilkeTextFieldItem hPad="xs" vPad={isCheckbox ? undefined : 'xs'}>
          {isCheckbox ? (
            <SilkeCheckbox
              disabled={disabled}
              readOnly={readonly}
              value={value || false}
              onChange={onChange}
            />
          ) : (
            <SilkeToggle
              disabled={disabled}
              readOnly={readonly}
              value={value || false}
              onChange={onChange}
              small
            />
          )}
        </SilkeTextFieldItem>
      </SilkeTextFieldOutline>
    </SilkeBox>
  );
};

export default Toggle;
