import React, { useMemo } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import type { LedgerLineItem } from '../types';
import { formatMoney } from '../utils/ledger';
import { lineItemsShowDetailColumns } from '../utils/ledger-batch-import';
import { LedgerDetailPopover, LedgerDetailTable } from './LedgerDetailPopover';

interface LedgerLineItemsCellProps {
  items: LedgerLineItem[];
  total: number;
  canEdit: boolean;
  reasonLabel: string;
  title: string;
  ariaLabel: string;
  onChange: (items: LedgerLineItem[]) => void;
}

const EMPTY_ITEM: LedgerLineItem = { reason: '', amount: 0, remark: '' };

function updateItem(
  items: LedgerLineItem[],
  index: number,
  patch: Partial<LedgerLineItem>,
): LedgerLineItem[] {
  const next = [...items];
  next[index] = { ...next[index], ...patch };
  return next;
}

function LedgerLineItemsEditor({
  items,
  reasonLabel,
  ariaLabel,
  onChange,
}: {
  items: LedgerLineItem[];
  reasonLabel: string;
  ariaLabel: string;
  onChange: (items: LedgerLineItem[]) => void;
}) {
  const rowCount = items.length;
  const showDetailColumns = lineItemsShowDetailColumns(items);

  return (
    <>
      <p className="ldb-detail-card-meta">
        {rowCount > 0 ? `共 ${rowCount} 条明细记录` : '暂无明细，请添加记录'}
      </p>
      <div className="ldb-detail-card-table-wrap ldb-line-items-table-wrap">
        <table className="ldb-detail-popover-table ldb-line-items-table">
          <thead>
            <tr>
              {showDetailColumns && <th>{reasonLabel}</th>}
              <th className="ldb-detail-col-amount">金额</th>
              {showDetailColumns && <th>备注</th>}
              <th className="ldb-line-items-col-action" aria-label="操作">操作</th>
            </tr>
          </thead>
          <tbody>
            {rowCount === 0 ? (
              <tr>
                <td colSpan={showDetailColumns ? 4 : 2} className="ldb-line-items-empty-cell">暂无明细</td>
              </tr>
            ) : items.map((item, index) => (
              <tr key={index}>
                {showDetailColumns && (
                  <td>
                    <input
                      type="text"
                      className="vm-input ldb-line-items-input"
                      value={item.reason}
                      placeholder={reasonLabel}
                      aria-label={`${ariaLabel} ${reasonLabel}`}
                      onChange={(event) => onChange(updateItem(items, index, { reason: event.target.value }))}
                    />
                  </td>
                )}
                <td className="ldb-detail-col-amount">
                  <input
                    type="number"
                    className="vm-input ldb-line-items-input ldb-line-items-input--amount tabular-nums"
                    value={item.amount || ''}
                    min={0}
                    step={0.01}
                    placeholder="0.00"
                    aria-label={`${ariaLabel} 金额`}
                    onChange={(event) => onChange(updateItem(items, index, { amount: Number(event.target.value) || 0 }))}
                  />
                </td>
                {showDetailColumns && (
                  <td>
                    <input
                      type="text"
                      className="vm-input ldb-line-items-input"
                      value={item.remark}
                      placeholder="备注"
                      aria-label={`${ariaLabel} 备注`}
                      onChange={(event) => onChange(updateItem(items, index, { remark: event.target.value }))}
                    />
                  </td>
                )}
                <td className="ldb-line-items-col-action">
                  <button
                    type="button"
                    className="ldb-line-items-row-delete"
                    aria-label={`删除第 ${index + 1} 行`}
                    onClick={() => onChange(items.filter((_, rowIndex) => rowIndex !== index))}
                  >
                    <Trash2 size={16} aria-hidden />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="ldb-line-items-toolbar">
        <button
          type="button"
          className="vm-btn vm-btn-ghost ldb-line-items-add"
          data-vm-icon="plus"
          onClick={() => onChange([...items, { ...EMPTY_ITEM }])}
        >
          添加一行
        </button>
      </div>
    </>
  );
}

export function LedgerLineItemsCell({
  items,
  total,
  canEdit,
  reasonLabel,
  title,
  ariaLabel,
  onChange,
}: LedgerLineItemsCellProps) {
  const displayItems = items.length > 0 ? items : [];
  const sum = total;
  const showDetailColumns = lineItemsShowDetailColumns(displayItems);

  const tableRows = useMemo(
    () => displayItems.map((item) => ({
      reason: item.reason,
      amount: formatMoney(item.amount),
      remark: item.remark,
    })),
    [displayItems],
  );

  const readColumns = showDetailColumns
    ? [
      { key: 'reason', title: reasonLabel },
      { key: 'amount', title: '金额', align: 'right' as const },
      { key: 'remark', title: '备注' },
    ]
    : [{ key: 'amount', title: '金额', align: 'right' as const }];

  const content = canEdit ? (
    <LedgerLineItemsEditor
      items={displayItems}
      reasonLabel={reasonLabel}
      ariaLabel={ariaLabel}
      onChange={onChange}
    />
  ) : (
    <LedgerDetailTable
      columns={readColumns}
      rows={tableRows}
      emptyText="暂无明细"
    />
  );

  return (
    <LedgerDetailPopover
      label={formatMoney(sum)}
      title={title}
      triggerClassName={canEdit ? 'ldb-line-items-trigger--editable' : ''}
    >
      {content}
    </LedgerDetailPopover>
  );
}
