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

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

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

function buildTooltip(tag: CustomerRiskTag): string {
  return [
    tag.tagName,
    `类型：${tag.tagCategoryName}`,
    `责任部门：${tag.responsibleDept}`,
    `风险级别：${tag.riskLevelName}`,
    `状态：${tag.statusName}`,
  ].join('\n');
}

const MAX_VISIBLE = 2;

export function RiskLabelTags({ tags, onView }: RiskLabelTagsProps) {
  const [open, setOpen] = useState(false);
  const visibleTags = getVisibleListTags(tags);
  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 shown = displayTags.slice(0, MAX_VISIBLE);
  const overflow = displayTags.length - MAX_VISIBLE;

  return (
    <span className="cm-risk-label-cell">
      {shown.map((tag) => (
        <button
          key={tag.id}
          type="button"
          className={`cm-risk-tag ${levelClass(tag.riskLevel)}`}
          onClick={onView}
          title={buildTooltip(tag)}
        >
          {tag.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)}
          onClick={onView}
          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-tooltip-row">
                  <span className={`cm-risk-tag ${levelClass(tag.riskLevel)}`}>{tag.tagName}</span>
                  <span className="cm-risk-tooltip-meta">
                    {tag.tagCategoryName} · {tag.riskLevelName} · {tag.statusName}
                  </span>
                </span>
              ))}
            </span>
          )}
        </span>
      )}
    </span>
  );
}