import React, { useEffect, useState } from 'react';
import { isEmpty } from 'lodash-es';
import IdentityName from 'src/components/shared/identity-name';
import TableBasic from 'src/components/shared/table-basic';

interface HoldHistoryItem {
    reason: string;
    startDate: string;
    endDate: string | null;
    lastModifiedBy: string;
    creatorName?: string | null;
}

export interface PaymentHoldHistoryProps {
    holdHistory: HoldHistoryItem[] | null;
    includeHeader?: boolean;
}

export default function PaymentHoldHistory({
    holdHistory,
    includeHeader,
}: PaymentHoldHistoryProps) {
    const [paymentHolds, setPaymentHolds] = useState<HoldHistoryItem[] | null>(
        null
    );

    useEffect(() => {
        if (holdHistory && !isEmpty(holdHistory) && !paymentHolds) {
            const holds = holdHistory.map(hold => ({
                ...hold,
                creatorName: null,
            }));
            setPaymentHolds(holds);
        }
    }, [holdHistory, paymentHolds]);
    const headers = ['Reason', 'Start Date', 'End Date', 'Created By'];

    const buildRows = () =>
        paymentHolds?.map((hold, index) => ({
            id: index,
            cols: [
                hold.reason,
                hold.startDate,
                hold.endDate,
                <IdentityName key={index} identity={hold.lastModifiedBy} />,
            ],
        })) ?? [];

    return (
        <div
            className="AccountDetail-hold-history"
            data-testid="accountPaymentHoldHistory"
        >
            {holdHistory && !isEmpty(holdHistory) && includeHeader && (
                <h3
                    className="AccountDetail-header"
                    data-testid="paymentHoldHistoryHeaderTestid"
                >
                    Hold History
                </h3>
            )}
            <div
                className="AccountDetail-payment-hold-history"
                data-testid="paymentHoldHistoryContentTestid"
            >
                {paymentHolds && !isEmpty(paymentHolds) && (
                    <TableBasic headers={headers} rows={buildRows()} />
                )}
            </div>
        </div>
    );
}
