import React from 'react';
import { TailwindPlayCommonParams } from '@/TailwindPlay/Fields/types.js';
import { ActionType } from '@/zeus/index.js';
import { evaluateSetValueRules } from '@/TailwindPlay/shared/rules.js';
import { extractHusarData } from '@/TailwindPlay/shared/extract.js';

export const FieldVariable: React.FC<TailwindPlayCommonParams> = (props) => {
  const { f, prefix = '', index } = props;
  const { v, attributes } = extractHusarData<{ label?: string; defaultValue?: string; shouldRender?: boolean }>(props);
  if (v?.shouldRender === false) {
    return null;
  }
  const key = `${prefix}${f.name}${typeof index === 'number' ? `[${index}]` : ''}`;
  const displayValue = evaluateSetValueRules(
    f,
    ActionType.DISPLAY_VALUE,
    props.state || {},
    props.modelData || {},
    prefix,
  );
  let content: string | undefined;
  if (displayValue !== undefined && displayValue !== null) {
    content = String(displayValue);
  } else {
    const stateValue = props.state?.[key];
    if (stateValue !== undefined && stateValue !== null) {
      content = String(stateValue);
    } else if (v?.defaultValue) {
      content = v.defaultValue;
    }
  }
  if (!content) return null;
  return (
    <div {...attributes} className={`tw-variable ${attributes.className || ''}`} data-field-type="variable">
      <div className="tw-variable-content">{content}</div>
    </div>
  );
};
