import React from 'react';
import { isEmpty } from 'lodash-es';
import TableBasic from 'src/components/shared/table-basic';
import type { AccountDetailAccountPayee } from 'src/types/abacus-account';

export interface PaymentHistoryItem {
    accountPayeeHistoryId: string;
    payoneerPayeeName: string;
    endDate?: string;
    lastModified: string;
}

export interface PayeeNameHistoryProps {
    accountPayee: AccountDetailAccountPayee;
    accountPayeeHistory: PaymentHistoryItem[];
}

export default function PayeeNameHistory({
    accountPayee,
    accountPayeeHistory,
}: PayeeNameHistoryProps) {
    const tableHeaders = ['Payee Name History', 'Start Date', 'End Date'];

    const formatRows = () => {
        let endDate = accountPayee.lastModified;
        let payeeName = accountPayee.payoneerPayeeName;
        let prevEndDate: string;
        const nameHistory: PaymentHistoryItem[] = [];

        if (!isEmpty(accountPayeeHistory))
            accountPayeeHistory.forEach(row => {
                if (row.payoneerPayeeName) {
                    if (row.payoneerPayeeName === payeeName) {
                        nameHistory.pop();
                        endDate = prevEndDate;
                    }
                    const historyRow = { ...row, endDate };
                    nameHistory.push(historyRow);
                }
                prevEndDate = endDate;
                endDate = row.lastModified;
                payeeName = row.payoneerPayeeName;
            });

        if (isEmpty(nameHistory))
            return [
                {
                    id: 1,
                    cols: [<i>There are no prior entries</i>, '-', '-'],
                },
            ];

        return nameHistory.map(historyItem => ({
            id: historyItem.accountPayeeHistoryId,
            cols: [
                historyItem.payoneerPayeeName,
                historyItem.lastModified,
                historyItem.endDate,
            ],
        }));
    };

    return (
        <div
            className="AccountDetail-payee-name-history"
            data-testid="payeeNameHistoryTestId"
        >
            <TableBasic headers={tableHeaders} rows={formatRows()} />
        </div>
    );
}
