import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DefaultRequestPagination, HeaderType, SortTypeKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useExtensionPayoutListMutation } from '@/entities/additional-service/api/payout/use-extension-payout-list-mutation';
import {
  ExtensionPayoutExcelParams,
  ExtensionPayoutExcelResponse,
  ExtensionPayoutListParams,
  ExtensionPayoutListResponse,
  PayoutContent,
  PayoutDisbursementStatus,
  PayoutSearchDateType
} from '@/entities/additional-service/model/payout/types';
import { JSX, useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import moment from 'moment';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { useExtensionPayoutExcelMutation } from '@/entities/additional-service/api/payout/use-extension-payout-excel-mutation';
import { PayoutFilter } from '@/entities/additional-service/ui/filter/payout-filter';
import { getPayoutDisbursementStatusBtnGroup } from '@/entities/additional-service/model/payout/constant';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { useTranslation } from 'react-i18next';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';
import { useStore } from '@/shared/model/store';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';
import { useExtensionAccessCheck } from '@/shared/lib/hooks/use-extension-access-check';
import useIntersectionObserver from '@/widgets/intersection-observer';

export const PayoutListPage = () => {
  // Access check
  const { hasAccess, AccessDeniedDialog } = useExtensionAccessCheck({
    extensionCode: 'PAYOUT'
  });
  const { navigate } = useNavigate();
  const { t } = useTranslation();
  const userMid = useStore.getState().UserStore.mid;

  const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
  const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
  const [listItems, setListItems] = useState<Array<PayoutContent>>([]);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>(userMid);
  const [searchDateType, setSearchDateType] = useState<PayoutSearchDateType>(PayoutSearchDateType.REQUEST_DATE);
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [status, setStatus] = useState<PayoutDisbursementStatus>(PayoutDisbursementStatus.ALL);
  const [minAmount, setMinAmount] = useState<number | undefined>();
  const [maxAmount, setMaxAmount] = useState<number | undefined>();
  const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

  const { mutateAsync: extensionPayoutList } = useExtensionPayoutListMutation();
  const { mutateAsync: extensionPayoutExcel } = useExtensionPayoutExcelMutation();
  const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if(entry.isIntersecting){
        if(onActionIntersect && !!pageParam.cursor){
          setOnActionIntersect(false);
          callList('page');
        } 
      }
    });
  };

	const { setTarget } = useIntersectionObserver({ 
    threshold: 1, 
    onIntersect 
  });

  useSetHeaderTitle(t('additionalService.payout.title'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const onClickToNavigation = () => {
    navigate(PATHS.additionalService.payout.request);
  };

  const callList = (type?: string) => {
    setOnActionIntersect(false);
    let listParams: ExtensionPayoutListParams = {
      mid: mid,
      searchDateType: searchDateType,
      fromDate: fromDate,
      toDate: toDate,
      status: status,
      minAmount: minAmount,
      maxAmount: maxAmount,
      page: {
				...pageParam,
				...{ sortType: sortType }
			}
    };
    if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }

    extensionPayoutList(listParams).then((rs: ExtensionPayoutListResponse) => {
      if(type === 'page'){
        setListItems([
          ...listItems,
          ...rs.content
        ]);
      }
      else{
        setListItems(rs.content);
      }
			if(rs.hasNext 
        && rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      ){
        setPageParam({
          ...pageParam,
          ...{ cursor: rs.nextCursor }
        });
      }
      else{
        setPageParam({
          ...pageParam,
          ...{ cursor: null }
        });
      }
      setOnActionIntersect(
        !!rs.hasNext 
        && rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      );
    });
  };

  const onClickToOpenEmailBottomSheet = () => {
    setEmailBottomSheetOn(true);
  };

  const onSendRequest = (selectedEmail?: string) => {
    if (selectedEmail) {
      const params: ExtensionPayoutExcelParams = {
        mid: mid,
        email: selectedEmail,
        fromDate: fromDate,
        toDate: toDate,
      };
      extensionPayoutExcel(params).then((rs: ExtensionPayoutExcelResponse) => {
        console.log('Excel Download Status:', rs);
      });
    }
    setEmailBottomSheetOn(false);
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };
  const onClickToDisbursementStatus = (val: PayoutDisbursementStatus) => {
    setStatus(val);
  };

  useEffect(() => {
    callList();
  }, [
    mid,
    searchDateType,
    fromDate,
    toDate,
    status,
    minAmount,
    maxAmount,
    sortType
  ]);

  const getListDateGroup = () => {
    let rs = [];
    let date = '';
    let list = [];
    for (let i = 0; i < listItems.length; i++) {
      let itemDateStr = '';
      if (searchDateType === PayoutSearchDateType.REQUEST_DATE) {
        itemDateStr = listItems[i]?.requestDate || '';
      } else if (searchDateType === PayoutSearchDateType.SETTLEMENT_DATE) {
        itemDateStr = listItems[i]?.settlementDate || '';
      }
      let itemDate = itemDateStr.substring(0, 8);
      if (i === 0) {
        date = itemDate;
      }
      if (date !== itemDate) {
        if (list.length > 0) {
          rs.push(
            <ListDateGroup
              additionalServiceCategory={AdditionalServiceCategory.Payout}
              mid={mid}
              key={date + '-' + i}
              date={date}
              items={list as any}
            ></ListDateGroup>
          );
        }
        date = itemDate;
        list = [];
      }
      list.push(listItems[i] as any);
    }
    if (list.length > 0) {
      rs.push(
        <ListDateGroup
          additionalServiceCategory={AdditionalServiceCategory.Payout}
          mid={mid}
          key={date + '-last'}
          date={date}
          items={list as any}
        ></ListDateGroup>
      );
    }
    return rs;
  };

  // if (!hasAccess) {
  //   return <AccessDeniedDialog />;
  // }

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <section className="summary-section">
              <div className="credit-controls">
                <div>
                  <input
                    className="credit-period"
                    type="text"
                    value={moment(fromDate).format('YYYY.MM.DD') + '-' + moment(toDate).format('YYYY.MM.DD')}
                    readOnly={true}
                  />
                  <button
                    className="filter-btn"
                    aria-label={t('common.filter')}
                    onClick={() => onClickToOpenFilter()}
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt={t('common.searchOptions')}
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label={t('common.download')}
                  onClick={() => onClickToOpenEmailBottomSheet()}
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt={t('common.download')}
                  />
                </button>
              </div>
              <div className="account-frame">
                <div className="credit-summary">
                  <div className="row">
                    <span className="label">{t('additionalService.payout.depositBalance')}</span>
                    <span className="amount22">
                      {t('home.money', { value: new Intl.NumberFormat('en-US').format(50000000) })}
                    </span>
                  </div>
                </div>
              </div>
            </section>

            <section className="filter-section">
              <SortTypeBox
                sortType={sortType}
                onClickToSort={onClickToSort}
              ></SortTypeBox>
              <div className="excrow mr-0">
                <div className="full-menu-keywords no-padding">
                  {
                    getPayoutDisbursementStatusBtnGroup(t).map((value: any, index: number) => (
                      <span
                        key={`key-service-code=${index}`}
                        className={`keyword-tag ${(status === value.value) ? 'active' : ''}`}
                        onClick={() => onClickToDisbursementStatus(value.value)}
                      >{value.name}</span>
                    ))
                  }
                </div>
              </div>
            </section>
            <section className="transaction-list">
              { getListDateGroup() }
            </section>
            <div ref={ setTarget }></div>
            <div className="apply-row">
              <button
                className="btn-50 btn-blue flex-1"
                onClick={() => onClickToNavigation()}
              >{t('additionalService.payout.requestTitle')}</button>
            </div>
          </div>
        </div>
      </main>
      <PayoutFilter
        filterOn={filterOn}
        setFilterOn={setFilterOn}
        mid={mid}
        searchDateType={searchDateType}
        fromDate={fromDate}
        toDate={toDate}
        status={status}
        minAmount={minAmount}
        maxAmount={maxAmount}
        setMid={setMid}
        setSearchDateType={setSearchDateType}
        setFromDate={setFromDate}
        setToDate={setToDate}
        setStatus={setStatus}
        setMinAmount={setMinAmount}
        setMaxAmount={setMaxAmount}
      ></PayoutFilter>
      <EmailBottomSheet
        bottomSheetOn={emailBottomSheetOn}
        setBottomSheetOn={setEmailBottomSheetOn}
        imageSave={false}
        sendEmail={true}
        sendRequest={onSendRequest}
      ></EmailBottomSheet>
    </>
  );
};