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

export const FieldCheckbox: React.FC<
  Omit<TailwindPlayCommonParams, 'setState'> & {
    value?: boolean;
    onChange?: (key: string, value: boolean) => void;
  }
> = ({ f, prefix = '', index, state, ...commonParams }) => {
  const { modelData, attributes, onChange, value } = commonParams;
  const key = `${prefix}${f.name}${typeof index === 'number' ? `[${index}]` : ''}`;
  const v = get(modelData, key) as ModelTypes['CheckboxField'] | 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}>
      <input
        id={key}
        type="checkbox"
        disabled={isDisabled}
        checked={typeof value === 'boolean' ? value : false}
        onChange={(e) => onChange?.(key, e.target.checked)}
        className={renderAttrs?.className || ''}
        defaultChecked={v?.defaultValue || false}
      />
      <label className={renderAttrs?.className || ''} htmlFor={key}>
        {v?.label}
      </label>
    </div>
  );
};
