import { BN } from '@ocap/util';
import { formatNumber, formatTime, formatAmount } from '@blocklet/payment-react';
import { useEffect } from 'react';
import type { InvoicePDFProps } from './types';
import { composeStyles } from './utils';
import { getInvoiceRows } from '../invoice/table';
import { applyStyles } from './styles';

export function InvoiceTemplate({ data, t }: InvoicePDFProps) {
  const { detail, summary } = getInvoiceRows(data, t);

  useEffect(() => {
    applyStyles();
  }, []);

  return (
    <div id="invoice-template" style={composeStyles('template')}>
      {/* Header */}
      <div
        style={{
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: '20px',
          marginBottom: '40px',
        }}>
        <div style={composeStyles('fs-20 bold')}>{t('admin.invoice.name')}</div>
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
          <img src={window.blocklet.appLogo} style={composeStyles('logo')} alt="logo" />
          <span style={composeStyles('block p-10')}>{window.blocklet.appName}</span>
        </div>
      </div>

      {/* Bill Info */}
      <div style={composeStyles('flex mt-60')}>
        <div style={composeStyles('w-60')}>
          <span style={composeStyles('bold dark mb-5')}>{t('admin.invoice.billTo')}</span>
          <span style={composeStyles('block mb-5')}>{data.customer.name}</span>
          <span style={composeStyles('bold fs-12')}>{`DID:ABT:${data.customer.did}`}</span>
        </div>
        <div style={composeStyles('w-40')}>
          <div style={composeStyles('flex mb-5')}>
            <div style={composeStyles('w-40')}>
              <span style={composeStyles('bold')}>{t('admin.invoice.number')}</span>
            </div>
            <div style={composeStyles('w-60')}>
              <span style={composeStyles('gray')}>{data.number}</span>
            </div>
          </div>
          <div style={composeStyles('flex mb-5')}>
            <div style={composeStyles('w-40')}>
              <span style={composeStyles('bold')}>{t('admin.invoice.paidAt')}</span>
            </div>
            <div style={composeStyles('w-60')}>
              <span style={composeStyles('gray')}>
                {formatTime((data.period_start || data.status_transitions?.paid_at || 0) * 1000)}
              </span>
            </div>
          </div>
          <div style={composeStyles('flex mb-5')}>
            <div style={composeStyles('w-40')}>
              <span style={composeStyles('bold')}>{t('admin.invoice.dueDate')}</span>
            </div>
            <div style={composeStyles('w-60')}>
              <span style={composeStyles('gray')}>{formatTime(data.period_end * 1000)}</span>
            </div>
          </div>
          <div style={composeStyles('flex mb-5')}>
            <div style={composeStyles('w-40')}>
              <span style={composeStyles('bold')}>{t('admin.paymentCurrency.name')}</span>
            </div>
            <div style={composeStyles('w-60')}>
              <span style={composeStyles('gray')}>
                {data.paymentCurrency.symbol} ({data.paymentMethod.name})
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Table Header */}
      <div style={composeStyles('mt-40 row flex')}>
        <div style={composeStyles('w-38 p-4-8')}>
          <span style={composeStyles('bold')}>{t('admin.subscription.product')}</span>
        </div>
        <div style={composeStyles('w-15 p-4-8')}>
          <span style={composeStyles('bold right')}>{t('common.quantity')}</span>
        </div>
        <div style={composeStyles('w-15 p-4-8')}>
          <span style={composeStyles('bold right')}>{t('payment.customer.invoice.unitPrice')}</span>
        </div>
        <div style={composeStyles('w-15 p-4-8')}>
          <span style={composeStyles('bold right')}>{t('common.discount')}</span>
        </div>
        <div style={composeStyles('w-17 p-4-8')}>
          <span style={composeStyles('bold right')}>{t('common.amount')}</span>
        </div>
      </div>

      {/* Table Content */}
      {detail.map((line) => {
        // Calculate discount amount for this line item using BN to avoid scientific notation (e.g. 1e+21)
        let itemDiscountAmount = new BN(0);
        if (line.raw.discount_amounts && line.raw.discount_amounts.length > 0) {
          line.raw.discount_amounts.forEach((discount: any) => {
            if (discount.amount) {
              itemDiscountAmount = itemDiscountAmount.add(new BN(String(discount.amount)));
            }
          });
        }

        return (
          <div key={line.id} style={composeStyles('row flex')}>
            <div style={composeStyles('w-38 p-4-8 pb-15')}>
              <span style={composeStyles('dark')}>
                {line.product}
                {line.credits && (
                  <span style={composeStyles('block gray fs-10 mt-5')}>
                    {formatNumber(line.credits.total)} {line.credits.currency}
                  </span>
                )}
              </span>
            </div>
            <div style={composeStyles('w-15 p-4-8 pb-15')}>
              <span style={composeStyles('dark right')}>{line.quantity}</span>
            </div>
            <div style={composeStyles('w-15 p-4-8 pb-15')}>
              <span style={composeStyles('dark right')}>{line.price || ''}</span>
            </div>
            <div style={composeStyles('w-15 p-4-8 pb-15')}>
              <span style={composeStyles('dark right')}>
                {!itemDiscountAmount.isZero()
                  ? `-${formatAmount(itemDiscountAmount.toString(), data.paymentCurrency.decimal)} ${
                      data.paymentCurrency.symbol
                    }`
                  : '-'}
              </span>
            </div>
            <div style={composeStyles('w-17 p-4-8 pb-15')}>
              <span style={composeStyles('dark right')}>{line.amount}</span>
            </div>
          </div>
        );
      })}

      {detail.length === 0 && (
        <div style={composeStyles('row flex')}>
          <div style={composeStyles('w-38 p-4-8 pb-15')}>
            <span style={composeStyles('gray')}>-</span>
          </div>
          <div style={composeStyles('w-15 p-4-8 pb-15')}>
            <span style={composeStyles('gray right')}>-</span>
          </div>
          <div style={composeStyles('w-15 p-4-8 pb-15')}>
            <span style={composeStyles('gray right')}>-</span>
          </div>
          <div style={composeStyles('w-15 p-4-8 pb-15')}>
            <span style={composeStyles('gray right')}>-</span>
          </div>
          <div style={composeStyles('w-17 p-4-8 pb-15')}>
            <span style={composeStyles('gray right')}>-</span>
          </div>
        </div>
      )}

      {/* Summary */}
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-end',
          float: 'right',
          paddingRight: '8px',
          marginTop: '8px',
          width: '100%',
          minWidth: '280px',
        }}>
        {summary.map((line) => {
          const isTotal = line.key === 'Total' || line.key === 'common.total' || line.key === 'payment.total';
          const showDivider = isTotal;

          return (
            <div key={line.key} style={{ width: '100%' }}>
              {showDivider && (
                <div
                  style={{
                    borderTop: '1px solid #e3e3e3',
                    width: '100%',
                    marginBottom: '8px',
                    marginTop: '4px',
                  }}
                />
              )}
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  width: '100%',
                  padding: '4px 0',
                  paddingRight: '8%',
                  gap: '20px',
                }}>
                <span style={composeStyles('bold')}>
                  {line.key.startsWith('common.') || line.key.startsWith('payment.') ? t(line.key) : line.key}
                </span>
                <span
                  style={{
                    ...composeStyles('bold dark text-right'),
                    minWidth: '80px',
                  }}>
                  {line.value}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
