"use client"
import React, { useEffect, useState } from 'react';

import { Spinner } from 'reactstrap';
import moment from 'moment';
import { APP_URL, DURATION_MAP, IMAGE_PATH, PaymentMethod } from '@/lib/appConstant';
import { STORAGE_KEYS } from '@/types/common';
import useResponsive from '@/hooks/useResponsive';
import { useTranslations } from 'use-intl';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { makeStyles } from 'tss-react/mui';
import { useRouter } from 'next/navigation';
import { getCompanyDomain, getPageMargin, getServicePath, getViewSettings } from '@/lib/redux/features/serviceAdmin';
import { doGetAuthInfo, getAuthInfo } from '@/lib/redux/features/auth';
import StorageHelper from '@/lib/storeHelper';
import { addTax10, formatThousandsNumber, handleGMOPayment, handleVeritransPayment } from '@/lib/utils';
import ModalConfirm from '../modal/modal-confirm';
import AppTable, { ColumnsType } from '../ui/table';
import { cancelUserRegisterSubscription, fetchSubscriptionList, fetchUserRegisteredSubscriptionPage, getIsListLoad, getPaginationSubscription, getRegisteredSubscriptionPage, getSubscriptionPage } from '@/lib/redux/features/subscription';
import CustomPagination from '../ui/custom-pagination';
import { RegisteredSubscriptionResponse } from '@/types/subscription';
import { showToast } from '../toast/showToast';
import { authorizeCharge, createOrderReceive, gmoCharge, resetCreateOrderReceive, resetGakkenPaymentInfo, resetHtml, resetPaymentStatus, setCacheCouponCode, setCacheSubscriptionId } from '@/lib/redux/features/payment';
import { Row, Col } from 'antd';
import InputField from '../ui/input/input-field';
import { CircleCheck } from 'lucide-react';
import { setIdRegisterSubscription } from '@/lib/redux/features/layout';
import AppLoading from '../ui/loading';

const FORM_MODAL = {
  DETAIL: 'DETAIL',
  REGISTER: 'REGISTER'
};
const Style: any = {
  rowCancel: {
    backgroundColor: '#bdbdbd'
  },
  button: {
    backgroundColor: '#00B27B',
    borderColor: '#00B27B'
  },
  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'
    },
    coverCard: {
      display: 'flex',
      overflowX: 'auto',
      paddingBottom: '10px'
    },
    customPaging: {
      width: '100%',
      justifyContent: 'center',
      marginTop: '10px !important'
    },
    contentGroupName: {
      width: '100%',
      display: 'flex',
      '& span': {
        width: '90%',
        wordWrap: 'break-word',
        overflowWrap: 'break-word',
        whiteSpace: 'normal'
      }
    }
  }
));

const UserTableSubscription = props => {
  const {
    isMegreLayout,
    // couponActions: {
    //   getCouponUser
    // },
    // paymentActions: {
    //   gmoCharge,
    //   authorizeCharge,
    //   resetHtml,
    //   resetPaymentStatus,
    //   createOrderReceive,
    //   resetGakkenPaymentInfo,
    //   setCacheCouponCode,
    //   setCacheSubscriptionId,
    //   resetCreateOrderReceive
    // },
    // notificationActions: {
    //   showNotification
    // },
    // sessionActions: {
    // //   getAuthInfo
    // }
  } = props;
  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { below768, getBelow768 } = useResponsive();

  const isPaymentSuccess = useAppSelector((state) => state.payment.isPaymentSuccess);
  const isPaymentError = useAppSelector((state) => state.payment.isPaymentError);
  const viewSettings = useAppSelector(getViewSettings);
  const authUser = useAppSelector(getAuthInfo);
  const servicePath = useAppSelector(getServicePath);
  const currentDomain = useAppSelector(getCompanyDomain);
  const isGMOPayment = viewSettings.paymentGateway === PaymentMethod.GMO;
  const isGakkenPayment = viewSettings.paymentGateway === PaymentMethod.GAKKEN_ID;

  const urlGakkenPayment = useAppSelector((state) => state.payment.redirectUrl);
  const isLoadingGakkenInfo = useAppSelector((state) => state.payment.isLoadingGakkenInfo);
  const isCreateOrderReceive = useAppSelector((state) => state.payment.isCreateOrderReceive);
  const isRediectUrl = useAppSelector((state) => state.payment.isRediectUrl);
  const registeredlist = useAppSelector(getRegisteredSubscriptionPage);
  const list = useAppSelector(getSubscriptionPage);
  
  const queries = useAppSelector(getPaginationSubscription);
  // const totalRecords = useAppSelector(getSubscriptionTotalRecords);
  // const totalPages = useAppSelector(getSubscriptionTotalPages);
  const isListLoad = useAppSelector(getIsListLoad);
  const { totalRecords = 0, totalPages = 0 } = queries;


  const [isListMode, setIsListMode] = useState(false);
  const [showFormModal, setShowFormModal] = useState('');
  const [isDetailMode, setIsDetailMode] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteModalMessage, setDeleteModalMessage] = useState('');
  const [selectedSubscription, setSelectedSubscription] = useState<any>();
  const [isOpenClose, setIsOpenClose] = useState(true);
  const [isLoadCreateOrderReceive, setIsLoadCreateOrderReceive] = useState(false);
  const [searchKey, setSearchKey] = useState('');
    



//   const { pathname } = useLocation();

  const pathname = '/subscription'
  const { classes } = useStyle();

  const cacheCouponCode = StorageHelper.getSessionItem(STORAGE_KEYS.couponCode);
  const cacheSubscriptionId = StorageHelper.getSessionItem(STORAGE_KEYS.subsId);
  const cacheGakkenRedirectUrl = StorageHelper.getSessionItem(STORAGE_KEYS.redirectUrlCallback);

  const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
  
  const isToken = StorageHelper.getCookie(userStore);
  
  const marginPage = useAppSelector(getPageMargin);

  useEffect(() => {
      dispatch(resetPaymentStatus());
      dispatch(resetGakkenPaymentInfo());
      setShowFormModal('');
      // if (isPaymentError || isPaymentSuccess) {
      //    setIsListMode(true);
      // }
  }, [isPaymentSuccess, isPaymentError]);
  /**
     * Total label for tables
     * @param from
     * @param to
     * @param size
     * @returns {*}
     */
  const customTotal = (from, to, size) => (
    <span className="react-bootstrap-table-pagination-total">
      {t('label.tableTotal', { from, to, size })}
    </span>
  );

  /**
     * Call data on page changed
     * @param page
     * @param sizePerPage
     */
  const handlePageChange = (page: number, sizePerPage?: number) => {
    const newQueries = { ...queries };
    newQueries.page = page;
    newQueries.searchKey = searchKey;
    if (sizePerPage) {
      newQueries.size = sizePerPage;
    }
    dispatch(fetchUserRegisteredSubscriptionPage(newQueries));
  };
  const pageListRenderer = ({
    pages,
    onPageChange
  }) => {
    // just exclude <, <<, >>, >
    const pageWithoutIndication = pages.filter(p => typeof p.page !== 'string');
    return (
      <ul className={`pagination react-bootstrap-table-page-btns-ul ${!isMegreLayout && below768 ? classes.customPaging : ''}`}>
        <li className={`page-item ${queries.page <= 1 ? 'disabled' : ''}`} onClick={() => onPageChange(1)} >
          <a className="page-link">{'<<'}</a>
        </li>
        <li className={`page-item ${queries.page <= 1 ? 'disabled' : ''}`} onClick={() => onPageChange(queries.page - 1)} >
          <a className="page-link">{'<'}</a>
        </li>
        {
          pageWithoutIndication.map(p => {
            if (p.page >= (queries.page - 3) && p.page <= (queries.page + 3)) {
              return (
                <li
                  className={`page-item ${queries.page === p.page ? 'active' : ''}`}
                  key={`page-${p.page}`}
                  onClick={() => onPageChange(p.page)}
                >
                  <a className="page-link"
                    style={{
                      backgroundColor: queries.page === p.page ? isMegreLayout ? '#00B27B' : '#007bff' : '',
                      borderColor: queries.page === p.page ? isMegreLayout ? '#00B27B' : '#007bff' : ''
                    }}
                  >
                    {p.page}
                  </a>
                </li>
              );
            }
            if (p.page - 4 === queries.page || p.page === queries.page - 4) {
              return (
                <li
                  className={`page-item ${queries.page === p.page ? 'active' : ''}`}
                  key={`page-${p.page}`}
                  onClick={() => onPageChange(p.page)}
                >
                  <a className="page-link">
                    {'...'}
                  </a>
                </li>
              );
            }
          })
        }
        <li className={`page-item ${queries.page >= totalPages ? 'disabled' : ''}`} onClick={() => onPageChange(queries.page + 1)} >
          <a className="page-link">{'>'}</a>
        </li>
        <li className={`page-item ${queries.page >= totalPages ? 'disabled' : ''}`} onClick={() => onPageChange(totalPages)} >
          <a className="page-link">{'>>'}</a>
        </li>
      </ul>
    );
  };


  // trigger event when the table has any data change here
  const onTableSearch = () => {
    const newQueries = { ...queries };
    newQueries.searchKey = searchKey;
    newQueries.page = 1;
    // setSearchKey(searchKey);
    dispatch(fetchUserRegisteredSubscriptionPage(newQueries));
  };

  const resetTable = () => {
    const newQueries = { ...queries };
    newQueries.page = 1;
    newQueries.size = 10;
    newQueries.searchKey = '';
    dispatch(fetchUserRegisteredSubscriptionPage(newQueries));
  };
  useEffect(() => {
    if (isToken) {
      isListMode ? dispatch(fetchSubscriptionList({ size: 100 })) : resetTable();
    }
  }, [isListMode]);

  /**
     * Handle delete pressed
     * @param data
     */
  const handleDelete = (data: any) => {
    setDeleteModalMessage(t('text.confirmCancel', { name: data.nameSubscriptionPlan }));
    setShowDeleteModal(true);
    setSelectedSubscription(data);
  };

  const doDeleteSubscription = () => {
    dispatch(cancelUserRegisterSubscription({
      data: { id: selectedSubscription.id },
      queries: queries
    }));
  };

  const handleDetail = (data: any) => {
    setSelectedSubscription(data);
    setIsDetailMode(true);
    // history.push(`/subscription/${data.subscriptionPlanId}`, { idRegister: data.id });
    dispatch(setIdRegisterSubscription(data.id))
    router.push(`${servicePath ? '/'+servicePath : ''}/subscription/${data.subscriptionPlanId}/?idRegister=${data.id}`);
  };

  // const headerFormatter = (col, row) => (
  //   <TranslateMessage id={col.text} />
  // );

  const renderActionsColumn = (row) => (
    isMegreLayout
      ? <React.Fragment>
        <span className="pointer nowrap mr-2" style={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={handleDetail.bind(this, row)}>
          {t('label.detail')}
        </span>
        {
          !row.cancel &&
      <span className="pointer nowrap" style={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={handleDelete.bind(this, row)}>
          {t('button.cancelSubscription')}
      </span>
        }

      </React.Fragment>
      : <React.Fragment>
        <span className="pointer nowrap text-info mr-2" onClick={handleDetail.bind(this, row)}>
          <i className="fas fa-edit" /> {t('label.detail')}
        </span>
        {
          !row.cancel &&
        <span className="pointer nowrap text-danger" onClick={handleDelete.bind(this, row)}>
          <i className="fa fa-trash" /> {t('button.cancelSubscription')}
        </span>
        }

      </React.Fragment>
  );

  const renderPriceColumn = (_: any, { price }: RegisteredSubscriptionResponse, index: number) => {
    return (
      <div>
        <span>{'¥' + formatThousandsNumber(price)}</span>
      </div>
    );
  };

  const renderColumnCenter = (value: any) => {
    return (
      <div className='text-center'>
        {value}
      </div>
    );
  };

  const columns: ColumnsType<RegisteredSubscriptionResponse> = [
    {
        title: t('label.plan'),
        dataIndex: "nameSubscriptionPlan",
        key: "nameSubscriptionPlan",
        // sorter: true,
        // width: "30%",
        render: (_, { nameSubscriptionPlan }) => {
            return (
                <div>
                    <span style={Style.itemMax} title={nameSubscriptionPlan}>{nameSubscriptionPlan}</span>
                </div>
            );
        },
    },
    {
        title: t('label.amount'),
        dataIndex: "price",
        key: "price",
        // sorter: true,
        // width: "30%",
        render: renderPriceColumn,
    },
    {
        title: t('label.status'),
        dataIndex: "status",
        key: "status",
        // sorter: true,
        // width: "30%",
        render: (_, { status }) => {
            return (
                <div>
                    <span>{t(`subscription.status.${status}`)}</span>
                </div>
            );
        },
    },
    {
        title: t('label.registeredDate'),
        dataIndex: "registeredDate",
        key: "registeredDate",
        // sorter: true,
        // width: "30%",
        render: (_, { createdDate }) => {
            return (
                <div>
                    <span>{moment.utc(createdDate).local().format('YYYY/MM/DD').toString()}</span>
                </div>
            );
        },
    },
    {
        title: t('label.freeDays'),
        dataIndex: "numberFreeTerm",
        key: "numberFreeTerm",
        // sorter: true,
        // width: "30%",
        render: (_, { numberFreeTerm }) => renderColumnCenter(numberFreeTerm),
    },
    {
        title: t('label.firstPayment'),
        dataIndex: "firstPaymentDate",
        key: "firstPaymentDate",
        // sorter: true,
        // width: "30%",
        render: (_, { cancel, firstPaymentDate }) => {
            return (
                <div>
                    {
                        !cancel 
                        ? firstPaymentDate ? (moment.utc(firstPaymentDate).local().format('YYYY/MM/DD').toString()) : <div style={{ marginLeft: !firstPaymentDate ? '30px' : '' }}>{'-'}</div> 
                        : <div style={{ margin: cancel ? '0 15px' : '' }}>{'-'}</div>
                    }
                </div>
            );
        },
    },
    {
        title: t('label.expiredDate'),
        dataIndex: "expiredDate",
        key: "expiredDate",
        // sorter: true,
        // width: "30%",
        render: (_, { cancel, expiredDate }) => {
            return (
                <div className='text-center'>
                    {
                        cancel
                        ? (moment.utc(expiredDate).local().format('YYYY/MM/DD').toString())
                        : <div style={{ margin: '0 20px' }}>{'-'}</div>
                    }
                </div>
            );
        },
    },
    {
        title: t('label.nextBillingDate'),
        dataIndex: "nextBillingDate",
        key: "nextBillingDate",
        // sorter: true,
        // width: "30%",
        render: (_, { cancel, nextRenewalDate }) => {
            return (
                <div className='text-center'>
                    {
                        !cancel
                        ? (moment.utc(nextRenewalDate).local().format('YYYY/MM/DD').toString())
                        : <div style={{ margin: cancel ? '0 20px' : '' }}>{'-'}</div>
                    }
                </div>
            );
        },
    },
    {
        title: t('label.cancelDate'),
        dataIndex: "cancelDate",
        key: "cancelDate",
        // sorter: true,
        // width: "30%",
        render: (_, { cancelDate }) => {
            return (
                <div className='text-center'>
                    {
                        cancelDate
                        ? (moment.utc(cancelDate).local().format('YYYY/MM/DD').toString())
                        : <div style={{ margin: !cancelDate ? '0 20px' : '' }}>{'-'}</div>
                    }
                </div>
            );
        },
    },
    {
        title: t('label.operations'),
        dataIndex: "operations",
        key: "operations",
        // sorter: true,
        // width: "30%",
        render: (_, data) => {
            return renderActionsColumn(data);
        },
    },
  ];

  const rowStyle = (row: any, rowIndex) => {
    const style: any = {};
    if (row.cancel) {
      style.backgroundColor = '#e7e7e7';
    }
    return style;
  };

  const handleCompletePayment = () => {
    dispatch(resetHtml());
    setShowFormModal('');
    dispatch(doGetAuthInfo());
    dispatch(fetchSubscriptionList({ size: 10, page: 1 }));
  };
  const handleErrorPayment = _errorMessage => {
    if (_errorMessage) {
      showToast("error", _errorMessage);
      // showToast({
      //   message: _errorMessage,
      //   level: 'error',
      //   autoDismiss: 3,
      //   position: 'tc'
      // });
      setShowFormModal('');
    }
  };

  const handleGmoCharge = (data: any) => {
    dispatch(gmoCharge(data));
  }

  const handleAuthorizeCharge = (data:any) => {
    dispatch(authorizeCharge(data))
  }
  const handleFormSubmit = (data: any) => {
    // Check if add mode
    if (showFormModal === FORM_MODAL.REGISTER) {
      const params = {
        ...data,
        authUser,
        subscriptionPlanId: data.id
      };
      // Do add
      if (isGMOPayment) {
        const errorMessage = handleGMOPayment(params, handleGmoCharge, handleErrorPayment);
        if (errorMessage) {
          showToast("error", errorMessage);
          // showNotification({
          //   message: errorMessage,
          //   level: 'error',
          //   autoDismiss: 3,
          //   position: 'tc'
          // });
          setShowFormModal('');
        }
      } else if (isGakkenPayment) {
        // setShowFormModal('');
        setIsLoadCreateOrderReceive(true);
        if (cacheSubscriptionId) {
          StorageHelper.removeSessionItem(STORAGE_KEYS.subsId);
        }
        if (cacheCouponCode) {
          StorageHelper.removeSessionItem(STORAGE_KEYS.couponCode);
        }
        if (cacheGakkenRedirectUrl) {
          StorageHelper.removeSessionItem(STORAGE_KEYS.redirectUrlCallback);
        }
        dispatch(createOrderReceive({ ...params, state: pathname, redirectUrl: `${window.location.origin}/${servicePath ? `${servicePath}/` : ''}gakken-payment/processing` }));
        // setCacheRedirectUrlCallback(redirectUrlGakkenPayment);
        if (data.couponCode) {
          dispatch(setCacheCouponCode(data.couponCode));
        }
        if (data.id) {
          dispatch(setCacheSubscriptionId(data.id));
        }
      } else {
        const errorMessage = handleVeritransPayment(params, handleAuthorizeCharge);
        if (errorMessage) {
          showToast("error", errorMessage);
          // showNotification({
          //   message: errorMessage,
          //   level: 'error',
          //   autoDismiss: 3,
          //   position: 'tc'
          // });
          setShowFormModal('');
        }
      }
    } else {
      setShowFormModal('');
    }
  };

  useEffect(() => {
    if (urlGakkenPayment) {
      setIsLoadCreateOrderReceive(false);
      if (isRediectUrl) {
        window.open(`${urlGakkenPayment}`, '_self');
      } else {
        dispatch(resetCreateOrderReceive());
      }
    }
    if (!isCreateOrderReceive && urlGakkenPayment === '') {
      setIsLoadCreateOrderReceive(false);
    }
  }, [urlGakkenPayment, isCreateOrderReceive]);

  return (
    <>
      <Row style={{
        width: '100%',
        marginTop: '3rem',
        margin: below768 ? '0px 10px' : '0',
        marginBottom: '1.5rem',
      }}>
        <Col
          span={10}
          style={{
            padding: '0 15px',
            marginLeft: below768 ? '10px' : isMegreLayout && marginPage.left ? marginPage.left : '0px',
            marginRight: below768 ? '10px' : isMegreLayout && marginPage.right ? marginPage.right : '0px'
          }}
        >
          <div className="mb-sm-3" >
            <button className="btn btn-info mr-1" style={{ ...Style.button, width: '100%' }}
              onClick={() => {
                setIsListMode(prevState => !prevState);
              }} disabled={isListLoad}
            >
              {
                !isListMode && t('button.registerPlan')
              }
              {
                isListMode && t('button.myRegisterPlan')
              }
            </button>
          </div>
          {
            !isListMode &&
            <div className="mt-sm-0 mt-2">
              <InputField
                type='search'
                value={searchKey}
                placeholder={t('label.search')}
                onChange={(value: string) => {setSearchKey(value)}}
                onSearch={onTableSearch}
                // isMegreLayout={isMegreLayout}
              />
            </div>
          }
        </Col>
      </Row>
      <div className="flex mb-3">
        <div className="col-sm-5 mb-sm-3" >
        </div>
      </div>

      {
        (isListLoad || isLoadingGakkenInfo) &&
        <div style={Style.spin}>
          <AppLoading/>
          {/* {t('progress.loading')} */}
        </div>
      }
      {
        (!isListMode && !isListLoad) && ((!below768 && isMegreLayout) || !isMegreLayout) &&
        <div style={{
          marginLeft: isMegreLayout && marginPage.left ? marginPage.left + 15 : '0px',
          marginRight: isMegreLayout && marginPage.right ? marginPage.right : '0px'
        }}>
          
          <AppTable<any>
            columns={columns}
            dataSource={registeredlist}
            loading={isListLoad}
            pagination={{
              current: queries.page,
              pageSize: queries.size || 0,
              total: totalRecords,
            }}
            rowKey="id"
            scroll={{ x: 1000 }}
            onChange={(page: any) => handlePageChange(page)}
            rowConfig={{
              style: {
                transition: "all 0.3s ease",
              },
            }}
          />
        </div>
      }
      {
        below768 && isMegreLayout && !isListMode && !isListLoad &&
        <>
          {registeredlist && registeredlist.map(item => {
            return (
              <Row key={item.id} style={{
                borderTop: '1px solid #d2d2d2',
                margin: below768 ? '0px 10px' : ''
              }}>
                <Col span={24} style={{ marginTop: 10, marginBottom: 10 }}>
                  <Row>
                    <Col span={12} style={{ textAlign: 'start', wordBreak: 'break-all' }}>
                      <span style={{ fontSize: 14, fontWeight: 'bold' }}>{item.nameSubscriptionPlan}</span>
                    </Col>
                    <Col span={12} style={{ textAlign: 'end' }}>
                      <span style={{ fontSize: 14 }}>{t(`subscription.status.${item.status}`)}</span>
                    </Col>
                  </Row>
                </Col>
                <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', paddingLeft: 0, paddingRight: 0 }}>
                  <div style={{
                    height: '115px',
                    width: '115px',
                    border: '1px solid #d0d0d0',
                    borderRadius: '5px'
                  }}>
                    <img
                      className={classes.imageSubscription}
                      src={APP_URL.UPLOAD_PATH + '/' + IMAGE_PATH.SUBSCRIPTION + item.imageSubscriptionPlan}
                    />
                  </div>
                </Col>
                <Col span={16}>
                  <Row>
                    <Col span={12} className="mb-2">
                      <span >{t('label.amount')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{'¥' + formatThousandsNumber(item.price)}</span>
                    </Col>
                    <Col span={12} className="mb-2">
                      <span >{t('label.registeredDate')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{(moment.utc(item.createdDate).local().format('YYYY/MM/DD').toString())}</span>
                    </Col>
                    <Col span={12} className="mb-2">
                      <span >{t('label.freeDays')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{item.numberFreeTerm}</span>
                    </Col>
                    <Col span={12} className="mb-2">
                      <span >{t( 'label.firstPayment')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{!item.cancel ? item.firstPaymentDate ? (moment.utc(item.firstPaymentDate).local().format('YYYY/MM/DD').toString()) : <div style={{ marginLeft: !item.firstPaymentDate ? '30px' : '' }}>{'-'}</div> : <div style={{ marginLeft: item.cancel ? '30px' : '' }}>{'-'}</div>}</span>
                    </Col>
                    <Col span={12} className="mb-2">
                      <span >{t( 'label.nextBillingDate')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{!item.cancel ? (moment.utc(item.expiredDate).local().format('YYYY/MM/DD').toString()) : <div style={{ marginLeft: item.cancel ? '45px' : '' }}>{'-'}</div>}</span>
                    </Col>
                    <Col span={12} className="mb-2">
                      <span >{t( 'label.cancelDate')}: </span>
                    </Col>
                    <Col span={12} className="mb-2" style={{ textAlign: 'right' }}>
                      <span>{item.cancelDate ? (moment.utc(item.cancelDate).local().format('YYYY/MM/DD').toString()) : <div style={{ marginLeft: !item.cancelDate ? '45px' : '' }}>{'-'}</div>}</span>
                    </Col>
                  </Row>
                </Col>
                <Col span={24} style={{ marginBottom: 10 }}>
                  <div style={{
                    display: 'flex',
                    flexDirection: 'row',
                    width: '100%'
                  }}>
                    <button className="btn btn-info w-full" style={{ backgroundColor: '#00B27B', borderColor: '#00B27B' }} onClick={handleDetail.bind(this, item)}>
                      {t('label.detail')}
                    </button>
                    {
                      !item.cancel &&
                      <button className="btn btn-danger w-full ml-10" style={{ marginLeft: 10 }} onClick={handleDelete.bind(this, item)}>
                        {t('button.cancelSubscription')}
                      </button>
                    }
                  </div>
                </Col>
              </Row>
            );
          })}
          <div style={{ borderTop: '1px solid #d2d2d2', margin: '10px 10px' }}/>
          <CustomPagination
            page={queries.page}
            totalPages={totalPages}
            onChangePage={page => {
              handlePageChange(page, queries.size);
            }}
          />
        </>
      }
      {
        (isListMode && !isListLoad && !isLoadingGakkenInfo) && <div className={classes.coverCard} style={{
          marginLeft: isMegreLayout && marginPage.left ? !below768 ? marginPage.left + 15 : '10px' : '0px',
          marginRight: isMegreLayout && marginPage.right ? !below768 ? marginPage.right : '10px' : '0px'
        }}>
          {
            isListMode && list.map(item => {
              return (
                <div key={item.id} className={item.id === list[0].id ? '' : 'ml-3'} style={Style.itemCard}>
                  <div className="card-header text-center">
                    <h4 className="text-bold">{item.name}</h4>
                    <h5 className="text-bold">
                      {
                        item.price !== item.discountPrice && (item.discountPrice || item.discountPrice === 0)
                          ? <del style={{ fontSize: '1rem', color: '#929292' }} className="mr-2">¥{formatThousandsNumber(addTax10(item.price))}</del>
                          : null
                      }
                    ¥{formatThousandsNumber(addTax10(item.discountPrice || item.discountPrice === 0 ? item.discountPrice : item.price))}
                      {` (${t( 'label.inclusiveTax', { value: '10%' })})`}
                    </h5>
                    <span>{item.duration + ' ' + t(`subscription.${DURATION_MAP.get(0)}`)}</span>
                    <button
                      className=" btn btn-xsm btn-round btn-block btn-success text-capitalize mt-2"
                      onClick={() => {
                        router.push(`${servicePath ? '/'+servicePath : ''}/subscription/${item.id}`);
                        // setSelectedSubscription(item);
                        // getSubscriptionDetail(item.id);
                        // setCouponUserNull();
                        // setShowFormModal(FORM_MODAL.REGISTER);
                        // setIsDetailMode(false);
                      }}
                    >
                      {t('label.detail')}
                    </button>
                  </div>
                  {
                    item.subscriptionDiscountType &&
                  <div className="p-0 w-full" style={{ display: 'flex', flexDirection: 'column', borderBottom: '1px solid rgba(0,0,0,.125)' }}>
                    <h5 className="justify-content-center my-2" style={{ display: 'flex' }}>{t('label.discountDetail')}</h5>
                    <p className="justify-content-center mb-2 px-2 text-center text-break" style={{ display: 'flex' }}>{t(item.subscriptionDiscountType === 'ORDINAL' ? 'text.discountMessageOrdinal' : 'text.discountMessage', { name: item.nameSubscription, discount: item.discount })}</p>
                  </div>
                  }
                  <div className="card-body p-0">
                    <ul className="list-group list-group-flush pb-1">
                      <h5 className="t-level-5 text-center my-2">{t('label.contentGroups')}</h5>
                      <div className="list-group-item">
                        {
                          item.subscriptionContentGroups && item.subscriptionContentGroups.map(contentGroup => {
                            return (
                              <div key={contentGroup.contentGroupId} className={classes.contentGroupName}>
                                <CircleCheck className="text-success mr-1" />
                                <span>
                                  {contentGroup.contentGroupName}
                                </span>
                              </div>
                            );
                          })
                        }
                      </div>
                    </ul>
                  </div>
                </div>
              );
            })
          }
        </div>
      }


      {/* <CommonModal
        isOpen={showFormModal === FORM_MODAL.DETAIL || showFormModal === FORM_MODAL.REGISTER}
        toggle={isOpenClose ? () => setShowFormModal('') : null}
        title={selectedSubscription ? selectedSubscription.nameSubscriptionPlan ? selectedSubscription.nameSubscriptionPlan : selectedSubscription.name : ''}
        size="lg"
        backdrop={'static'}
      >
        <SubscriptionFormDetail
          onCancel={() => setShowFormModal('')}
          onSubmit={handleFormSubmit}
          detailMode={isDetailMode}
          completePayment={handleCompletePayment}
          showNotification={showNotification}
          resetPaymentStatus={resetPaymentStatus}
          setIsOpenClose={setIsOpenClose}
          getCouponUser={getCouponUser}
          isCreateOrderReceive={isLoadCreateOrderReceive}
        />
      </CommonModal> */}
      <ModalConfirm
        isOpen={showDeleteModal}
        toggle={() => setShowDeleteModal(false)}
        title={t('title.cancelSubscription')}
        message={deleteModalMessage}
        doConfirm={doDeleteSubscription}
        doCancel={() => setShowDeleteModal(false)}
        backdrop={'static'}
        level={'danger'}
        cancelButtonName={'button.cancelSubscriptionPlan'}
      />
    </>
  );
};


export default UserTableSubscription;
