import { Input } from '@tarojs/components';
import type { MlTextActiveInputProps } from './types';
import { classNames } from 'mixlea-utils-js';
import { useMemoFn, useDebounceFn } from 'mixlea-hooks-react';

export function ActiveInput(props: MlTextActiveInputProps) {
  const initialValue = props.value;

  const paddingLeft = props.paddingLeft ?? props.paddingX;
  const paddingRight = props.paddingRight ?? props.paddingX;

  const handleInput = useDebounceFn((e) => {
    const inputValue = e.detail.value.trim();

    if (inputValue !== initialValue) {
      props.onChange({ value: inputValue.trim() }, { dataset: props.dataset });
    }
  }, 500);

  const handleConfirm = useMemoFn((e) => {
    const inputValue = e.detail.value.trim();

    if (inputValue !== initialValue) {
      props.onChange({ value: inputValue.trim() }, { dataset: props.dataset });
    }
  });

  const handleBlur = useMemoFn((e) => {
    const inputValue = e.detail.value.trim();

    if (inputValue !== initialValue) {
      props.onChange({ value: inputValue.trim() }, { dataset: props.dataset });
    }

    props.onBlur();
  });

  return (
    <Input
      focus
      value={props.value}
      className={classNames('h-full w-full box-border p-0', {
        'pl-base': paddingLeft,
        'pr-base': paddingRight,
      })}
      onInput={handleInput}
      onConfirm={handleConfirm}
      onBlur={handleBlur}
    />
  );
}
