import { Tag } from 'antd';
import { useCommonCodes } from '@/hooks/useCommonCodes';

interface Props {
  groupCode: string;
  value?: string;
}

/**
 * 09_UI_DESIGN.md §5 CodeBadge — 4단계 색상 (success/info/warning/danger/default).
 * antd preset 대신 직접 컬러 + 옅은 배경으로 명확한 시각 구분.
 */
type Tone = 'success' | 'info' | 'warning' | 'danger' | 'default';

const TONE_MAP: Record<string, Tone> = {
  // 초록 — 긍정적 완료
  CONFIRMED: 'success', APPROVED: 'success', ACTIVE:    'success',
  PAID:      'success', COMPLETED: 'success', MATCH:    'success',
  MATCHED:   'success', DONE:      'success', SUCCESS:  'success',

  // 파랑 — 진행 중
  CALCULATED: 'info', PENDING:    'info', PROCESSING: 'info',
  REVIEWED:   'info', NEW:        'info', SENT:       'info',

  // 주황 — 주의
  HOLD:     'warning', SUSPEND:  'warning', MISMATCH: 'warning',
  PARTIAL:  'warning', DIFF:     'warning',

  // 빨강 — 부정적
  REJECTED: 'danger', LEAVE:    'danger', CANCEL:   'danger',
  FAILED:   'danger', FAIL:     'danger', LAPSED:   'danger',
  LAPSE:    'danger', LOCKED:   'danger',

  // 회색 — 기본
  DRAFT: 'default', READY: 'default', RETIRED: 'default',
};

const STYLE_MAP: Record<Tone, { color: string; bg: string; border: string }> = {
  success: { color: '#0F6E56', bg: '#E1F5EE', border: '#B9E5D5' },
  info:    { color: '#185FA5', bg: '#E6F1FB', border: '#BFDDF6' },
  warning: { color: '#BA7517', bg: '#FAEEDA', border: '#F1D9A8' },
  danger:  { color: '#E24B4A', bg: '#FCEBEB', border: '#F4C8C8' },
  default: { color: '#666666', bg: '#F5F5F5', border: '#DDDDDD' },
};

export default function CodeBadge({ groupCode, value }: Props) {
  const { data = [] } = useCommonCodes(groupCode);
  if (!value) return null;
  const code = data.find((c) => c.code === value);
  const label = code?.codeName ?? value;
  const tone = TONE_MAP[value] ?? 'default';
  const s = STYLE_MAP[tone];
  return (
    <Tag
      style={{
        color: s.color,
        background: s.bg,
        border: `1px solid ${s.border}`,
        margin: 0,
        padding: '0 8px',
        height: 22,
        lineHeight: '20px',
        fontSize: 12,
        fontWeight: 500,
        borderRadius: 4,
      }}
    >
      {label}
    </Tag>
  );
}
