import React, { useMemo } from 'react';
import type { BillCandidate, BillType, EnrichedLinkedBill, LinkedBill } from '../types';
import { BILL_TYPE_LABELS } from '../types';
import { calcBillUnreceivedAmount, enrichLinkedBills, formatMoney } from '../utils/payment';

const BILL_TYPE_SHORT: Record<BillType, string> = {
  lease: '租赁',
  'self-operated': '自营',
  clearing: '氢费',
};

interface LinkedBillsNestedTableProps {
  linkedBills: LinkedBill[];
  billPool: BillCandidate[];
  paymentCustomerName?: string;
}

function renderBillType(type: LinkedBill['type']) {
  return (
    <span
      className={`pr-bill-type-tag pr-bill-type-tag--${type}`}
      title={BILL_TYPE_LABELS[type]}
    >
      {BILL_TYPE_SHORT[type]}
    </span>
  );
}

function renderBillInfo(row: EnrichedLinkedBill) {
  const customerName = row.customerName || '—';
  const contractCode = row.contractCode || '—';
  const projectName = row.projectName || '—';
  const title = [customerName, contractCode, projectName].join(' / ');

  return (
    <div className="vm-stack pr-linked-bill-info" title={title}>
      <span className="primary">{customerName}</span>
      <span className="code tabular-nums">{contractCode}</span>
      <span className="sub">{projectName}</span>
    </div>
  );
}

export function LinkedBillsNestedTable({
  linkedBills,
  billPool,
  paymentCustomerName,
}: LinkedBillsNestedTableProps) {
  const rows = useMemo(
    () => enrichLinkedBills(linkedBills, billPool, paymentCustomerName),
    [linkedBills, billPool, paymentCustomerName],
  );

  if (rows.length === 0) {
    return <div className="lc-contract-vehicle-expand__empty">暂无关联账单</div>;
  }

  return (
    <div className="lc-contract-vehicle-table-wrap pr-linked-bill-table-wrap">
      <table className="lc-contract-vehicle-native-table pr-linked-bill-native-table">
        <thead>
          <tr>
            <th scope="col" className="pr-linked-bill-native-table__type">类型</th>
            <th scope="col" className="pr-linked-bill-native-table__info">项目信息</th>
            <th scope="col" className="pr-linked-bill-native-table__period">账期</th>
            <th scope="col" className="pr-linked-bill-native-table__money">应收</th>
            <th scope="col" className="pr-linked-bill-native-table__money">认领</th>
            <th scope="col" className="pr-linked-bill-native-table__money">未收</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row: EnrichedLinkedBill) => {
            const unreceived = calcBillUnreceivedAmount(row.receivable, row.allocatedAmount);
            return (
            <tr key={`${row.type}:${row.id}`}>
              <td className="pr-linked-bill-native-table__type">{renderBillType(row.type)}</td>
              <td className="pr-linked-bill-native-table__info">{renderBillInfo(row)}</td>
              <td className="pr-linked-bill-native-table__period tabular-nums">{row.period || '—'}</td>
              <td className="pr-linked-bill-native-table__money tabular-nums">
                {row.receivable != null ? formatMoney(row.receivable) : '—'}
              </td>
              <td className="pr-linked-bill-native-table__money tabular-nums">
                {formatMoney(row.allocatedAmount)}
              </td>
              <td className={`pr-linked-bill-native-table__money tabular-nums${unreceived != null && unreceived < 0 ? ' pr-bill-unreceived--negative' : ''}`}>
                {unreceived != null ? formatMoney(unreceived) : '—'}
              </td>
            </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
