import type { Elements } from '../config/map/values';
import { useStoreValue } from './hooks';
import { useStatus } from '@/stores/calculation/statuses/hooks';
import { useValidation } from '@/stores/calculation/validation/hooks';
import type { Values } from '@/stores/calculation/values/types';
import { observer } from 'mobx-react-lite';
import type { ChangeEvent, ComponentType } from 'react';
import { Form } from 'ui/elements';

type BuilderProps = {
  elementName: Elements;
  valueName: Values;
};

export function buildValue<T>(
  Component: ComponentType<T>,
  { elementName, valueName }: BuilderProps
) {
  return observer((props: T) => {
    const [value, setValue] = useStoreValue(valueName);
    const status = useStatus(elementName);
    const { validateStatus, help } = useValidation(elementName);

    return (
      <Form.Item help={help} validateStatus={validateStatus}>
        <Component
          onChange={(e: ChangeEvent<HTMLInputElement>) => {
            setValue(e.target.value);
          }}
          disabled={status === 'Disabled'}
          value={value}
          {...props}
        />
      </Form.Item>
    );
  });
}

export function buildNumberValue<T>(
  Component: ComponentType<T>,
  { elementName, valueName }: BuilderProps
) {
  return observer((props: T) => {
    const [value, setValue] = useStoreValue(valueName);
    const status = useStatus(elementName);
    const { validateStatus, help } = useValidation(elementName);

    return (
      <Form.Item help={help} validateStatus={validateStatus}>
        <Component
          onChange={(inputValue: number | null) => {
            setValue(inputValue || 0);
          }}
          disabled={status === 'Disabled'}
          value={value}
          {...props}
        />
      </Form.Item>
    );
  });
}
