import React, { useState } from 'react';
import FieldLabel from './FieldLabel';
import {
  AUTO_INJECTED_CONTEXT_ITEMS,
  buildStepOutputRef,
  detectReferenceCycles,
  dynamicChipLabel,
  dynamicTooltip,
  formatCycleWarning,
  getSelectableStepOutputRefs,
  stepOutputLabel,
} from './variableUtils';

function AutoInjectedItem({ item }) {
  const [showPopover, setShowPopover] = useState(false);

  return (
    <span
      className="studio-var-auto-chip"
      onMouseEnter={() => setShowPopover(true)}
      onMouseLeave={() => setShowPopover(false)}
      onFocus={() => setShowPopover(true)}
      onBlur={() => setShowPopover(false)}
      tabIndex={0}
    >
      <span className="studio-var-auto-chip__label">{item.label}</span>
      {showPopover && (
        <span className="studio-var-auto-chip__popover" role="tooltip">
          {item.description}
        </span>
      )}
    </span>
  );
}

function VariableSwitch({ label, selected, onToggle, tooltip }) {
  return (
    <label
      className={`studio-var-switch ${selected ? 'studio-var-switch--on' : ''}`}
      title={tooltip}
    >
      <span className="studio-var-switch__label">{label}</span>
      <span className="studio-var-switch__track" aria-hidden="true">
        <input
          type="checkbox"
          className="studio-var-switch__input"
          checked={selected}
          onChange={onToggle}
        />
        <span className="studio-var-switch__thumb" />
      </span>
    </label>
  );
}

export default function VariableChips({
  pipeline,
  selectedNode,
  onToggleRef,
  variant = 'default',
}) {
  const isCompact = variant === 'compact';
  const [autoExpanded, setAutoExpanded] = useState(false);

  const previousSteps = getSelectableStepOutputRefs(pipeline, selectedNode);
  const cycleWarning = formatCycleWarning(detectReferenceCycles(pipeline), pipeline);

  const isChecked = (ref) =>
    (selectedNode.inputs || []).some((i) => i.ref === ref);

  return (
    <div className={`studio-var-panel ${isCompact ? 'studio-var-panel--compact' : ''}`}>
      <h3 className="studio-var-panel__title">
        <FieldLabel tip="引用前序步骤的世界书条目；核心目的、思考流程等由系统自动注入">
          上文引用
        </FieldLabel>
      </h3>

      {cycleWarning && (
        <p className="studio-var-cycle-warn" role="alert">
          {cycleWarning}
        </p>
      )}

      <div className="studio-var-group studio-var-group--auto">
        <button
          type="button"
          className="studio-var-auto-toggle"
          onClick={() => setAutoExpanded((v) => !v)}
          aria-expanded={autoExpanded}
        >
          <span className="studio-var-group__title">系统自动注入</span>
          <span className="studio-var-auto-toggle__meta">
            {autoExpanded
              ? '收起'
              : `${AUTO_INJECTED_CONTEXT_ITEMS.length} 项已默认注入`}
          </span>
          <span className="studio-var-auto-toggle__chevron" aria-hidden="true">
            {autoExpanded ? '▾' : '▸'}
          </span>
        </button>

        {autoExpanded ? (
          <div className="studio-var-auto-list">
            {AUTO_INJECTED_CONTEXT_ITEMS.map((item) => (
              <AutoInjectedItem key={item.id} item={item} />
            ))}
          </div>
        ) : (
          <p className="studio-edit-hint studio-var-auto-hint">
            运行时自动附带，无需手动开启。展开可查看各项含义。
          </p>
        )}
      </div>

      <div className="studio-var-group">
        <h4 className="studio-var-group__title">前序步骤产物</h4>
        <p className="studio-edit-hint studio-var-manual-hint">
          开关开启后，将把对应步骤的最终世界书条目注入本步上下文。
        </p>
        <div className={`studio-var-grid ${isCompact ? 'studio-var-grid--compact' : ''}`}>
          {previousSteps.length === 0 ? (
            <p className="studio-edit-hint studio-var-empty">暂无可引用的前序世界书步骤</p>
          ) : (
            previousSteps.map((node) => {
              const ref = buildStepOutputRef(node.id);
              const checked = isChecked(ref);
              const label = dynamicChipLabel(ref, pipeline, stepOutputLabel(node.displayName));
              return (
                <VariableSwitch
                  key={ref}
                  label={label}
                  selected={checked}
                  tooltip={dynamicTooltip(ref, pipeline)}
                  onToggle={() =>
                    onToggleRef(ref, stepOutputLabel(node.displayName))
                  }
                />
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}
