import React from 'react';
import { CircleHelp } from 'lucide-react';
import type { LeaseKpiSummary, ListViewMode } from '../types';
import { formatMoney } from '../utils/ledger';

const CARDS: Array<{
  key: keyof LeaseKpiSummary;
  title: string;
  desc: string;
  money?: boolean;
  clickable?: boolean;
  viewMode?: ListViewMode;
}> = [
  {
    key: 'count',
    title: '台账条数',
    desc: '业务服务组员工仅统计本人录入；主管统计全组汇总。点击可切换列表为显示全部数据。',
    clickable: true,
    viewMode: 'all',
  },
  { key: 'receivableTotal', title: '应收总计', desc: '当前筛选范围内应收合计之和', money: true },
  { key: 'receivedAmount', title: '实收总计', desc: '当前筛选范围内实收金额之和', money: true },
  {
    key: 'unreceived',
    title: '未收总计',
    desc: '当前筛选范围内未收金额之和。点击可筛选下方列表仅显示未收款数据。',
    money: true,
    clickable: true,
    viewMode: 'unpaid',
  },
  { key: 'totalCost', title: '成本总计', desc: '当前筛选范围内总成本之和', money: true },
  { key: 'profitLoss', title: '盈亏总计', desc: '当前筛选范围内盈亏之和', money: true },
];

interface LedgerKpiRowProps {
  summary: LeaseKpiSummary;
  listViewMode: ListViewMode;
  onListViewChange: (mode: ListViewMode) => void;
}

export function LedgerKpiRow({ summary, listViewMode, onListViewChange }: LedgerKpiRowProps) {
  return (
    <div className="ldb-kpi-row" data-annotation-id="lbl-kpi">
      {CARDS.map((card) => {
        const raw = summary[card.key];
        const value = card.money ? formatMoney(raw) : String(raw);
        const profitClass = card.key === 'profitLoss'
          ? (summary.profitLoss >= 0 ? 'ldb-kpi-val--profit' : 'ldb-kpi-val--loss')
          : '';
        const isActive = card.clickable && card.viewMode === listViewMode;

        const inner = (
          <>
            <span className="ldb-kpi-tip" tabIndex={0} aria-label={`${card.title}说明`}>
              <CircleHelp size={14} aria-hidden />
              <span className="ldb-kpi-tooltip" role="tooltip">{card.desc}</span>
            </span>
            <span className="ldb-kpi-label">{card.title}</span>
            <span className={`ldb-kpi-val tabular-nums ${profitClass}`}>{value}</span>
          </>
        );

        if (card.clickable && card.viewMode) {
          return (
            <button
              key={card.key}
              type="button"
              className={`ldb-kpi-card ldb-kpi-card--clickable ${isActive ? 'ldb-kpi-card--active' : ''}`}
              data-annotation-id={card.key === 'count' ? 'lbl-kpi-count' : 'lbl-kpi-unreceived'}
              onClick={() => onListViewChange(card.viewMode!)}
              aria-pressed={isActive}
            >
              {inner}
            </button>
          );
        }

        return (
          <div key={card.key} className="ldb-kpi-card">
            {inner}
          </div>
        );
      })}
    </div>
  );
}
