import get from 'lodash-es/get';
import { ModelTypes } from '@/zeus/index.js';
import { TailwindPlayCommonParams } from '@/TailwindPlay/Fields/types.js';
import { evaluateConditionNode, NON_INTERACTIVE_ACTIONS } from '../shared/rules';

export const FieldInput: React.FC<
  Omit<TailwindPlayCommonParams, 'setState'> & {
    value?: string;
    onChange?: (key: string, value: string) => void;
  }
> = ({ f, prefix = '', index, state, ...commonParams }) => {
  const { modelData, attributes, value, onChange } = commonParams;
  const key = `${prefix}${f.name}${typeof index === 'number' ? `[${index}]` : ''}`;
  const v = get(modelData, key) as ModelTypes['InputField'] | undefined;
  const dataFieldName = key.replace(/\[\d+\]/g, '').replace(/^\./, '');
  const renderAttrs = (get(attributes, key) as { className?: string; component?: string } | undefined) || f.visual;
  const notInteractiveActions = (f.visual?.rules || []).filter(
    (rule) => rule.actions && rule.actions.some((action) => NON_INTERACTIVE_ACTIONS.includes(action.type)),
  );
  const isDisabled = notInteractiveActions.some((rule) =>
    rule.conditions?.every((condition) =>
      evaluateConditionNode(f, condition, state || {}, modelData || {}, prefix || ''),
    ),
  );
  return (
    <div className={renderAttrs?.className || ''} data-field-name={dataFieldName}>
      <label htmlFor={key}>{v?.label}</label>
      <input
        disabled={isDisabled}
        type={v?.type || 'text'}
        placeholder={v?.placeholder || undefined}
        defaultValue={v?.defaultValue || undefined}
        name={key}
        value={value}
        onChange={(e) => {
          onChange?.(key, e.target.value);
        }}
      />
    </div>
  );
};
