import React from 'react';
import { Pencil, Trash2 } from 'lucide-react';
import { VisibilityRule } from '../types';
import { formatVisibilityRuleDescription, isVisibilityRuleEnabled } from '../utils';

interface VisibilityRuleSummaryProps {
  rule: VisibilityRule;
  onEdit: () => void;
  onDelete: () => void;
  onToggleEnabled?: () => void;
}

/** 将 {变量} 或「内容值」高亮展示 */
function renderRuleDescription(rule: VisibilityRule) {
  const text = formatVisibilityRuleDescription(rule);
  if (rule.target === 'content') {
    const parts = text.split('内容值');
    if (parts.length === 1) return text;
    return parts.flatMap((part, i) =>
      i === 0
        ? [<span key={`${i}-t`}>{part}</span>, <span key={`${i}-c`} className="var-token">内容值</span>]
        : [<span key={`${i}-t`}>{part}</span>]
    );
  }
  const parts = text.split(/(\{[^}]+\})/g);
  return parts.map((part, i) =>
    part.startsWith('{') && part.endsWith('}') ? (
      <span key={i} className="var-token">
        {part}
      </span>
    ) : (
      <span key={i}>{part}</span>
    )
  );
}

export const VisibilityRuleSummary: React.FC<VisibilityRuleSummaryProps> = ({
  rule,
  onEdit,
  onDelete,
  onToggleEnabled,
}) => {
  const enabled = isVisibilityRuleEnabled(rule);

  return (
    <div className={`visibility-rule-summary${enabled ? '' : ' is-disabled'}`}>
      {onToggleEnabled && (
        <input
          type="checkbox"
          checked={enabled}
          onChange={onToggleEnabled}
          className="ps-checkbox shrink-0"
          title={enabled ? '禁用条件' : '启用条件'}
          aria-label={enabled ? '禁用条件' : '启用条件'}
        />
      )}
      <button
        type="button"
        onClick={onEdit}
        className="visibility-rule-summary-btn"
        title="编辑条件"
      >
        <p className="visibility-rule-summary-text">{renderRuleDescription(rule)}</p>
      </button>
      <button
        type="button"
        onClick={onEdit}
        title="编辑"
        className="shrink-0 p-1 rounded text-[#666] hover:text-[#31a8ff] hover:bg-[#333] transition-colors"
      >
        <Pencil className="w-3 h-3" />
      </button>
      <button
        type="button"
        onClick={onDelete}
        title="删除条件"
        className="shrink-0 p-1 rounded text-[#666] hover:text-red-400 hover:bg-[#3a2020] transition-colors"
      >
        <Trash2 className="w-3.5 h-3.5" />
      </button>
    </div>
  );
};
