import React, { useEffect, useState } from 'react';
import { Spinner } from 'reactstrap';
import moment from 'moment';
import { APP_URL, IMAGE_PATH, LAYOUT_SETTING } from '@/lib/appConstant';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { getCompanyDomain, getLayoutViewPage, getPageMargin, getServicePath } from '@/lib/redux/features/serviceAdmin';
import { useTranslations } from 'use-intl';
import useResponsive from '@/hooks/useResponsive';
import StorageHelper from '@/lib/storeHelper';
import { makeStyles } from 'tss-react/mui';
import { formatThousandsNumber } from '@/lib/utils';
import InputField from '../ui/input/input-field';
import CustomPagination from '../ui/custom-pagination';
import AppTable, { ColumnsType } from '../ui/table';
import { fetchPaymentHisotryPage, getIsLoadingTransaction, getTransactionList, getTransactionPagination } from '@/lib/redux/features/transaction';
import { TransactionResponse } from '@/types/transaction';
import { Col, Row } from 'antd';
import AppLoading from '../ui/loading';

const Style = {
  spin: {
    display: 'flex',
    justifyContent: 'center'
  },
  itemMax: {
    maxWidth: 300,
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis'
    // display: 'inline-block'
  },
  coverCard: {
    display: 'flex',
    overflowX: 'auto',
    paddingBottom: '10px'
  },
  itemCard: {
    width: '300px',
    minWidth: 300,
    display: 'flex',
    flexDirection: 'column',
    backgroundColor: '#fff',
    border: '1px solid rgba(0, 0, 0, 0.125)',
    borderRadius: '0.25rem'
  }

};

const useStyle = makeStyles()(() => (
    {
      header: {
        border: 'none',
        '& td': {
          border: 'none'
        },
        '& th': {
          border: 'none'
        }
      },
      imageSubscription: {
        height: '100%',
        width: '100%',
        objectFit: 'contain'
      },
      customPaging: {
        width: '100%',
        justifyContent: 'center',
        marginTop: '10px !important'
      }
    }
));

const UserTablePaymentHistory = (props: any) => {
    const {
        // transactionActions: {
        //     getPaymentHistoryPage
        // }
    } = props;


    const t = useTranslations("");
    const dispatch = useAppDispatch();
    const { below768, getBelow768 } = useResponsive();

    const layoutViewPage = useAppSelector(getLayoutViewPage);
    const servicePath = useAppSelector(getServicePath);
    const currentDomain = useAppSelector(getCompanyDomain);
    const marginPage = useAppSelector(getPageMargin);
    const list = useAppSelector(getTransactionList);
    const queries = useAppSelector(getTransactionPagination);
    const isLoading = useAppSelector(getIsLoadingTransaction);

    const { totalPages = 0, totalRecords = 0 } = queries
    const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
    const isToken = StorageHelper.getCookie(userStore);
    const isLayout3 = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
    


    const [searchKey, setSearchKey] = useState('');

    const { classes } = useStyle();

     const renderPriceColumn = (_: any, { price }: TransactionResponse, index: number) => {
       return (
         <div>
           <span>{'¥' + formatThousandsNumber(price)}</span>
         </div>
       );
     };
    const renderStatusColumn = (_: any, { status }: TransactionResponse, index: number ) => {
        let value = '';
        switch (status) {
            case 'SUCCESS':
                value = t('label.ok');
                break;
            case 'PENDING':
                value = t('label.pending');
                break;
            case 'CANCEL':
                value = t('subscription.status.CANCEL');
                break;
            case 'REFUNDED':
                value = t('label.ok');
                break;
        
            default:
                value = t('label.ng');
                break;
        }
        return (
            <div className='text-center'>{value}</div>
        );
    };
    const columns: ColumnsType<TransactionResponse> = [
        {
            title: t('label.plan'),
            dataIndex: "subscriptionPlanName",
            key: "subscriptionPlanName",
            // sorter: true,
            // width: "30%",
            render: (_, { subscriptionPlanName }) => {
                return (
                    <div>
                        <span style={Style.itemMax} title={subscriptionPlanName}>{subscriptionPlanName}</span>
                    </div>
                );
            },
        },
        {
            title: t('label.amount'),
            dataIndex: "price",
            key: "price",
            // sorter: true,
            // width: "30%",
            render: renderPriceColumn
        },
        {
            title: t('label.date'),
            dataIndex: "createdDate",
            key: "createdDate",
            // sorter: true,
            // width: "30%",
            render: (_, { numberFreeTerm, firstPaymentDate, createdDate }) => {
                return (
                    <div>
                        {
                            numberFreeTerm > 0
                            ? (moment.utc(firstPaymentDate).local().format('YYYY/MM/DD').toString())
                            : (moment.utc(createdDate).local().format('YYYY/MM/DD').toString())
                        }
                    </div>
                );
            },
        },
        {
            title: t('label.status'),
            dataIndex: "status",
            key: "status",
            // sorter: true,
            // width: "30%",
            render: renderStatusColumn
        }
    ];

    useEffect(() => {
        if (isToken) {
            dispatch(fetchPaymentHisotryPage({ page: 1, size: 10 }));
        }
    }, [isToken]);

    const handlePageChange = (page: number, sizePerPage?: number) => {
        const newQueries = { ...queries };
        newQueries.page = page;
        newQueries.searchKey = searchKey;
        if (sizePerPage) {
            newQueries.size = sizePerPage;
        }
        dispatch(fetchPaymentHisotryPage(newQueries));
    };

//   const pagination = paginationFactory({
//     page: queries.page,
//     sizePerPage: queries.size,
//     totalSize: totalRecords,
//     paginationSize: totalPages,
//     alwaysShowAllBtns: true,
//     hideSizePerPage: true,
//     showTotal: true,
//     paginationTotalRenderer: customTotal,
//     pageListRenderer: pageListRenderer,
//     onPageChange: handlePageChange
//   });

  // trigger event when the table has any data change here
   
    const onTableSearch = () => {
        const newQueries = { ...queries };
        newQueries.searchKey = searchKey.trim();
        newQueries.page = 1;
        setSearchKey(searchKey.trim());
        dispatch(fetchPaymentHisotryPage(newQueries));
    };

    return (
        <div className="row mb-3" style={{
            marginTop: '1rem',
            marginLeft: below768 ? '10px' : isLayout3 && marginPage.left ? marginPage.left : '0',
            marginRight: below768 ? '10px' : isLayout3 && marginPage.right ? marginPage.right : '0'
        }}>
            <div className="col-sm-12 col-md-5 mt-sm-0 mt-2" style={{ margin: '10px 0' }}>
                <InputField
                    type='search'
                    value={searchKey}
                    placeholder={t('label.search')}
                    onChange={(value: string) => {setSearchKey(value)}}
                    onSearch={onTableSearch}
                    // isMegreLayout={isMegreLayout}
                />
                {/* <InputSearch
                    id="user-group-search"
                    searchText={queries.search_key}
                    onSearch={onTableSearch}
                    isLayout3={isLayout3}
                /> */}
            </div>
            <div className="col-sm-12 mt-sm-0 mt-2" style={{ margin: '10px 10px' }}/>
            {
                isLoading &&
                <div style={Style.spin}>
                    <AppLoading/>
                </div>
            }
            {(!isLoading && list && ((!below768 && isLayout3) || !isLayout3)) &&
            <div className="col-sm-12 col-md-12 mt-sm-0 mt-2">
                <AppTable<any>
                    columns={columns}
                    dataSource={list}
                    loading={isLoading}
                    pagination={{
                        current: queries.page,
                        pageSize: queries.size || 0,
                        total: totalRecords,
                    }}
                    rowKey="id"
                    scroll={{ x: 1000 }}
                    onChange={(page: any, size: any, param3) => {
                        handlePageChange(page, size)
                    }}
                    rowConfig={{
                        style: {
                            transition: "all 0.3s ease",
                        },
                    }}
                />
            </div>
            }
            {
                below768 && isLayout3 && !isLoading && list &&
                <>
                    {list.map(item => {
                        return (
                            <Row key={`history-${item.id}`} style={{ borderTop: '1px solid #d2d2d2', padding: isLayout3 ? '0 15px' : '', width: '100%' }}>
                                <Col span={8} style={{ marginTop: 10, marginBottom: 10 }}>
                                    <div style={{ height: 115, width: 115, border: '1px solid #d0d0d0', borderRadius: 5 }}>
                                        <img
                                            className={classes.imageSubscription}
                                            src={APP_URL.UPLOAD_PATH + '/' + IMAGE_PATH.SUBSCRIPTION + item.subscriptionImage}
                                        />
                                    </div>
                                </Col>
                                <Col span={16} style={{ marginTop: 10, marginBottom: 10, display: 'flex' }}>
                                    <Row style={{ width: '100%' }}>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14, fontWeight: 600 }}>{item.subscriptionPlanName}</span>
                                        </Col>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14 }}>
                                                {
                                                    item.status === 'SUCCESS'
                                                    ? t('label.ok')
                                                    : item.status === 'PENDING'
                                                        ? t('label.pending')
                                                        : item.status === 'CANCEL'
                                                            ? t('subscription.status.CANCEL')
                                                            : item.status === 'REFUNDED'
                                                                ? t( 'label.ok')
                                                                : t( 'label.ng')
                                                }
                                            </span>
                                        </Col>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14, fontWeight: 600 }}>{`${t( 'label.amount')}:`}</span>
                                        </Col>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14 }}>{`${'¥' + formatThousandsNumber(item.price)}`}</span>
                                        </Col>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14, fontWeight: 600 }}>{`${t( 'label.date')}:`}</span>
                                        </Col>
                                        <Col span={12}>
                                            <span style={{ fontSize: 14 }}>{item.numberFreeTerm > 0 ? (moment.utc(item.firstPaymentDate).local().format('YYYY/MM/DD').toString()) : (moment.utc(item.createdDate).local().format('YYYY/MM/DD').toString())}</span>
                                        </Col>

                                    </Row>
                                </Col>
                            </Row>
                        );
                    })}
                    <div style={{ borderTop: '1px solid #d2d2d2', margin: '10px 0px' }}/>
                    <CustomPagination
                        page={queries.page}
                        totalPages={totalPages}
                        onChangePage={(page: any) => {
                            handlePageChange(page, queries.size);
                        }}
                    />
                </>}
        </div>
    );
};

export default UserTablePaymentHistory;
