import React, { useState } from 'react';
import dayjs from 'dayjs';
import { GridTable, Section } from '@theorchard/suite-components';
import { useFeatureFlag } from '@theorchard/suite-frontend';
import { ABACUS_ACTIONS, YYYY_MM_DD } from '@theorchard/accounting-apps-shared';
import { useCustomPayments } from 'src/apollo/queries/custom-payment';
import PaymentDescription from 'src/components/shared/payment-description';
import { paymentStatus } from 'src/components/shared/payment-status';
import {
    DEFAULT_ITEMS_PER_PAGE,
    NO_PAYMENTS_RESULTS,
    USER_FEATURES,
} from 'src/constants';
import { smartFormatter } from 'src/utils/amount-helpers';
import { getStatusMessage } from 'src/utils/payment-overview';
import type { CellProps } from '@theorchard/suite-components/dist/esm/src/components/table/base/types';
import type { GetCustomPaymentsQuery } from 'src/apollo/queries/custom-payment/__generated__/get-custom-payments';
import { getValueOrEmptyChar } from 'src/utils/get-value-or-empty-char';

type CustomPayment = GetCustomPaymentsQuery['customPayments']['items'][0];

const CustomPayments: React.FC = () => {
    const isTablesRevampEnabled = useFeatureFlag(
        USER_FEATURES.TAP_PAYMENT_TABLES_REVAMP
    );
    const [pageSize, setPageSize] = useState(DEFAULT_ITEMS_PER_PAGE);
    const [page, setPage] = useState(0);

    const { data, loading } = useCustomPayments(pageSize, page * pageSize);

    const customPayments = data?.customPayments;
    const items = customPayments?.items || [];
    const totalCount = customPayments?.totalCount || 0;

    const tableExtraProps = isTablesRevampEnabled
        ? {
              variant: 'zebra' as const,
              stickyHeader: true,
          }
        : {};
    const table = (
        <GridTable
            bordered
            className="CustomPaymentsTable"
            columnDefs={[
                {
                    name: 'actionStates.actionStatus',
                    title: 'Status',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>{paymentStatus(data.actionStates)}</>
                    ),
                },
                {
                    name: 'dateSent',
                    title: 'Date Sent',
                    Cell: ({ data }: CellProps<CustomPayment>) => {
                        const eventDate = data.abacusEvents.find(
                            e => e.eventName === ABACUS_ACTIONS.SEND_PAYMENTS
                        )?.eventDate;
                        return (
                            <>
                                {getValueOrEmptyChar(
                                    eventDate
                                        ? dayjs
                                              .utc(eventDate)
                                              .format(YYYY_MM_DD)
                                        : undefined
                                )}
                            </>
                        );
                    },
                },
                {
                    name: 'paymentName',
                    title: 'Payment Name',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <PaymentDescription
                            worksheetPaymentCustomId={
                                data.worksheetPaymentCustomId
                            }
                            paymentName={data.paymentName}
                        />
                    ),
                },
                {
                    name: 'contract',
                    title: 'Contract (Name & ID)',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>
                            {data.contract.contractName} (
                            {data.contract.contractId})
                        </>
                    ),
                },
                {
                    name: 'account',
                    title: 'Account (Name & ID)',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>
                            {data.account.accountName} ({data.account.accountId}
                            )
                        </>
                    ),
                },
                {
                    name: 'amount',
                    title: 'Pre-Tax Amount',
                    align: 'right',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>{smartFormatter(data.amount, data.currencyCode)}</>
                    ),
                },
                {
                    name: 'amountAfterWithholdingAndVat',
                    title: 'Post-Tax Amount',
                    align: 'right',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>
                            {smartFormatter(
                                data.amountAfterWithholdingAndVat,
                                data.currencyCode
                            )}
                        </>
                    ),
                },
                {
                    name: 'statusDetails',
                    title: 'Status Details',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>
                            {getValueOrEmptyChar(
                                getStatusMessage(data.actionStates)
                            )}
                        </>
                    ),
                },
                {
                    name: 'createdAt',
                    title: 'Date Created',
                    Cell: ({ data }: CellProps<CustomPayment>) => (
                        <>{dayjs.utc(data.createdAt).format(YYYY_MM_DD)}</>
                    ),
                },
            ]}
            data={items}
            emptyStateTitle={NO_PAYMENTS_RESULTS}
            loading={loading}
            loadingRows={DEFAULT_ITEMS_PER_PAGE}
            onPageChange={setPage}
            onPageSizeChange={setPageSize}
            page={page}
            pageSize={pageSize}
            paginated
            showUpdateIndicator
            stickyHeader
            totalCount={totalCount}
            rowKey="worksheetPaymentCustomId"
            {...tableExtraProps}
        />
    );

    if (isTablesRevampEnabled) {
        return (
            <Section>
                <Section.Body>
                    <Section.Table>{table}</Section.Table>
                </Section.Body>
            </Section>
        );
    }

    return table;
};

export default CustomPayments;
