import React, { useState } from 'react';
import type { CustomerRiskTag } from '../types/riskTag';
import { getActiveTags, getPendingTags } from '../utils/riskTagStore';

interface RiskLabelTagsProps {
  tags: CustomerRiskTag[];
  onView?: () => void;
}

function levelClass(level: CustomerRiskTag['riskLevel']): string {
  switch (level) {
    case '低': return 'cm-risk-tag--low';
    case '中': return 'cm-risk-tag--medium';
    case '高': return 'cm-risk-tag--high';
    case '极高': return 'cm-risk-tag--critical';
    default: return 'cm-risk-tag--medium';
  }
}

export function RiskLabelTags({ tags, onView }: RiskLabelTagsProps) {
  const [open, setOpen] = useState(false);
  const visibleTags = tags.filter((tag) =>
    tag.status === '生效中' || tag.status === '待审批' || tag.status === '待确认',
  );
  const active = getActiveTags(visibleTags);
  const pending = getPendingTags(visibleTags);
  const displayTags = active.length > 0 ? active : pending;

  if (!displayTags.length) {
    return <span className="cm-muted">—</span>;
  }

  const primary = displayTags[0];
  const overflow = displayTags.length - 1;

  return (
    <span className="cm-risk-label-cell">
      <button
        type="button"
        className={`cm-risk-tag ${levelClass(primary.riskLevel)}`}
        onClick={onView}
        title={primary.tagName}
      >
        {primary.tagName}
      </button>
      {pending.length > 0 && active.length === 0 && (
        <span className="cm-risk-tag-pending" title="待审批/待确认">审</span>
      )}
      {overflow > 0 && (
        <span
          className="cm-risk-tag-count"
          onMouseEnter={() => setOpen(true)}
          onMouseLeave={() => setOpen(false)}
          onFocus={() => setOpen(true)}
          onBlur={() => setOpen(false)}
          tabIndex={0}
          role="button"
          aria-label={`还有 ${overflow} 个标签`}
        >
          +{overflow}
          {open && (
            <span className="cm-label-tooltip cm-risk-tag-tooltip" role="tooltip">
              {displayTags.map((tag) => (
                <span key={tag.id} className={`cm-risk-tag ${levelClass(tag.riskLevel)}`}>
                  {tag.tagName}
                  {tag.status !== '生效中' && (
                    <span className="cm-risk-tag-status">{tag.status}</span>
                  )}
                </span>
              ))}
            </span>
          )}
        </span>
      )}
      {pending.length > 0 && active.length > 0 && (
        <span className="cm-risk-tag-pending" title={`${pending.length} 个待审批`}>
          +{pending.length}审
        </span>
      )}
    </span>
  );
}
