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 { PayoutDisbursementStatusBtnGroup } from '@/entities/additional-service/model/payout/constant';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
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 = () => {
  // 권한 체크
  const { hasAccess, AccessDeniedDialog } = useExtensionAccessCheck({
    extensionCode: 'PAYOUT'
  });
  const { navigate } = useNavigate();
  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>(0);
  const [maxAmount, setMaxAmount] = useState<number>(50000000);
  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){
        console.log('Element is now intersecting with the root. [' + onActionIntersect + ']');
        if(onActionIntersect && !!pageParam.cursor){
          callList('page');
        } 
      }
      else{
        console.log('Element is no longer intersecting with the root.');
      }
    });
  };

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

  useSetHeaderTitle('지급대행');
  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.content.length === DEFAULT_PAGE_PARAM.size
      ){
        setPageParam({
          ...pageParam,
          ...{ cursor: rs.nextCursor }
        });
      }
      else{
        setPageParam({
          ...pageParam,
          ...{ cursor: null }
        });
      }
      setOnActionIntersect(
        !!rs.hasNext 
        && 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="필터"
                    onClick={() => onClickToOpenFilter()}
                  >
                    <img
                      src={IMAGE_ROOT + '/ico_setting.svg'}
                      alt="검색옵션"
                    />
                  </button>
                </div>
                <button
                  className="download-btn"
                  aria-label="다운로드"
                  onClick={() => onClickToOpenEmailBottomSheet()}
                >
                  <img
                    src={IMAGE_ROOT + '/ico_download.svg'}
                    alt="다운로드"
                  />
                </button>
              </div>
              <div className="account-frame">
                <div className="credit-summary">
                  <div className="row">
                    <span className="label">예치금 잔액</span>
                    <span className="amount22">
                      50,000,000<span className="unit">원</span>
                    </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">
                  {
                    PayoutDisbursementStatusBtnGroup.map((value, index) => (
                      <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()}
              >지급대행 신청</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>
    </>
  );
};