import React, { type PropsWithChildren, useEffect, useState } from 'react';
import { GridTable, Section } from '@theorchard/suite-components';
import { useFeatureFlag } from '@theorchard/suite-frontend';
import { useWorksheetPaymentContractAdvances } from 'src/apollo/queries/payment-group-payment';
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 PaymentDescription from '../shared/payment-description';
import type { CellProps } from '@theorchard/suite-components/dist/esm/src/components/table/base/types';

const AdvancePayments: 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 [totalCount, setTotalCount] = useState(0);
    const [requestParams, setRequestParams] = useState({
        limit: pageSize,
        offset: page * pageSize,
    });

    const { data, loading } =
        useWorksheetPaymentContractAdvances(requestParams);

    const worksheetPaymentContractAdvances =
        data?.worksheetPaymentContractAdvances;
    const items = worksheetPaymentContractAdvances?.items || [];

    useEffect(() => {
        if (worksheetPaymentContractAdvances) {
            setTotalCount(worksheetPaymentContractAdvances.totalCount || 0);
        }
    }, [worksheetPaymentContractAdvances, loading, requestParams]);

    useEffect(() => {
        setRequestParams({
            ...requestParams,
            limit: pageSize,
            offset: page * pageSize,
        });
    }, [page, pageSize]);

    const tableExtraProps = isTablesRevampEnabled
        ? {
              variant: 'zebra' as const,
              stickyHeader: true,
          }
        : {};
    const table = (
        <GridTable
            bordered
            className="AdvancePaymentsTable"
            columnDefs={[
                {
                    name: 'actionStates.actionStatus',
                    title: 'Status',
                    Cell: props => paymentStatus(props.data.actionStates),
                },
                {
                    name: 'actionStates.actionStatus.message',
                    title: 'Status Details',
                    Cell: props => (
                        <>{getStatusMessage(props.data.actionStates) || '-'}</>
                    ),
                },
                {
                    name: 'paymentName',
                    title: 'Payment Name',
                    Cell: ({
                        data: {
                            paymentName,
                            contractAdvance,
                            worksheetPaymentContractAdvanceId,
                        },
                    }: PropsWithChildren<CellProps<any>>) => {
                        return (
                            <PaymentDescription
                                worksheetPaymentContractAdvanceId={
                                    worksheetPaymentContractAdvanceId
                                }
                                paymentName={paymentName}
                                referencePaymentTypeId={
                                    contractAdvance.referencePaymentType
                                        .referencePaymentTypeId
                                }
                            />
                        );
                    },
                },
                {
                    name: 'contractAdvance.referencePaymentType.paymentType',
                    title: 'Payment Type',
                    className: 'paymentType',
                },
                {
                    name: 'contractAdvance.contract.contractName',
                    title: 'Contract Name',
                },
                {
                    name: 'contractAdvance.contract.account.accountName',
                    title: 'Account Name',
                },
                {
                    name: 'contractAdvance.createdAt',
                    title: 'Date created',
                },
                {
                    name: 'amount',
                    title: 'Amount',
                    Cell: ({ data }) => (
                        <>
                            {smartFormatter(
                                data.amount.convertedAmount.amount,
                                data.amount.convertedAmount.currencyCode
                            )}
                        </>
                    ),
                },
            ]}
            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="worksheetPaymentContractAdvanceId"
            {...tableExtraProps}
        />
    );

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

    return <div>{table}</div>;
};

export default AdvancePayments;
