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 '@/TailwindPlay/shared/rules.js';

export const FieldLink: React.FC<
  Omit<TailwindPlayCommonParams, 'setState'> & {
    value?: string;
    onChange?: (key: string, value: string) => void;
  }
> = ({ f, prefix = '', index, state, ...commonParams }) => {
  const { modelData, attributes } = commonParams;
  const key = `${prefix}${f.name}${typeof index === 'number' ? `[${index}]` : ''}`;
  const v = get(modelData, key) as ModelTypes['LinkField'] | undefined;
  const dataFieldName = key.replace(/\[\d+\]/g, '').replace(/^\./, '');
  const renderAttrs = (get(attributes, key) as { className?: string; component?: string } | undefined) || f.visual;

  const href = v?.href || '#';
  const target = v?.target || undefined;

  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 (
    <a
      href={href}
      target={target}
      className={renderAttrs?.className || ''}
      aria-disabled={isDisabled}
      style={isDisabled ? { pointerEvents: 'none', opacity: 0.6 } : undefined}
      data-field-name={dataFieldName}
    >
      {v?.label}
    </a>
  );
};
