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 type { SwitchChangeEventHandler } from 'antd/lib/switch';
import { observer } from 'mobx-react-lite';
import type { ComponentType } from 'react';
import { Form } from 'ui/elements';

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

export function buildSwitch<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={
            ((checked) => {
              setValue(checked);
            }) as SwitchChangeEventHandler
          }
          disabled={status === 'Disabled'}
          checked={value}
          {...props}
        />
      </Form.Item>
    );
  });
}
