import React from 'react';
import { Alert, GridTable, SkeletonLoader } from '@theorchard/suite-components';
import { useAbacusAccountTaxInfoHistoryQuery } from 'src/apollo/queries/account-payee-tax-info-history';
import { getFullCountryName } from './components/taxFormInfoCompleted/helpers';

interface Props {
    accountId: string;
}

export const CLASS_NAME = 'TaxInfoHistory';

export const TaxInfoHistory: React.FC<Props> = ({ accountId }) => {
    const { data, loading, error } = useAbacusAccountTaxInfoHistoryQuery({
        accountId,
    });

    if (loading) return <SkeletonLoader numberOfItems={4} vertical />;

    if (error)
        return (
            <Alert
                title="Error"
                text={'Error loading Tax Information history.'}
                variant="error"
            />
        );

    const history = data?.abacusAccount?.accountTaxInfoHistory ?? [];

    const tableData = history.map(item => ({
        accountTaxInfoHistoryId: item?.accountTaxInfoHistoryId,
        country: getFullCountryName(item?.countryOfTaxResidence),
        created: item?.createdAt,
        modified: item?.lastModified,
    }));

    const deduplicatedTableData = tableData.filter((item, index, self) => {
        return (
            self.findIndex(
                t =>
                    t.country === item.country &&
                    t.created === item.created &&
                    t.modified === item.modified
            ) === index
        );
    });

    return (
        <div className={CLASS_NAME} data-testid={CLASS_NAME}>
            <hr />
            <h4>History</h4>
            <GridTable
                rowKey="accountTaxInfoHistoryId"
                variant="zebra"
                data={deduplicatedTableData}
                columnDefs={[
                    {
                        name: 'country',
                        title: 'Country Of Tax Residence History',
                    },
                    { name: 'created', title: 'Start Date' },
                    { name: 'modified', title: 'End Date' },
                ]}
            />
        </div>
    );
};

export default TaxInfoHistory;
