import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType, SortByKeys } from '@/entities/common/model/types';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { 
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useEffect, useState } from 'react';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { 
  AlimtalkAlimCl,
  AlimtalkListContent, 
  AlimtalkSearchCl, 
  AlimTalkSendCl, 
  AlimtalkSendType,
  ExtensionAlimtalkDownloadExcelParams,
  ExtensionAlimtalkDownloadExcelResponse,
  ExtensionAlimtalkListParams,
  ExtensionAlimtalkListResponse
} from '@/entities/additional-service/model/alimtalk/types';
import moment from 'moment';
import { useExtensionAlimtalkListMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-list-mutation';
import { useExtensionAlimtalkDownloadExcelMutation } from '@/entities/additional-service/api/alimtalk/use-extansion-alimtalk-download-excel-mutation';
import { ListDateGroup } from '@/entities/additional-service/ui/list-date-group';
import { AdditionalServiceCategory } from '@/entities/additional-service/model/types';

export const AlimtalkListPage = () => {
  const { navigate } = useNavigate();

  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<Record<string, Array<AlimtalkListContent>>>({});
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest001m');
  const [searchCl, setSearchCl] = useState<AlimtalkSearchCl>(AlimtalkSearchCl.BUYER_NAME);
  const [searchValue, setSearchValue] = useState<string>();
  const [paymentMethod, setPaymentMethod] = useState<string>();
  const [alimCl, setAlimCl] = useState<AlimtalkAlimCl>(AlimtalkAlimCl.DEPOSIT_REQUEST);
  const [fromDate, setFromDate] = useState<string>(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState<string>(moment().format('YYYYMMDD'));
  const [sendType, setSendType] = useState<AlimtalkSendType>(AlimtalkSendType.ALL);
  const [sendCl, setSendCl] = useState<AlimTalkSendCl>(AlimTalkSendCl.ALL);
   
  const { mutateAsync: extensionAlimtalkList } = useExtensionAlimtalkListMutation();
  const { mutateAsync: extensionAlimtalkDownloadExcel } = useExtensionAlimtalkDownloadExcelMutation();

  useSetHeaderTitle('알림톡 결제통보');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const callList = (option?: {
      sortBy?: string, 
      val?: string
    }) => {
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);

    let params: ExtensionAlimtalkListParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      paymentMethod: paymentMethod,
      fromDate: fromDate,
      toDate: toDate,
      sendType: sendType,
      sendCl: sendCl,
      page: pageParam
    };
    extensionAlimtalkList(params).then((rs: ExtensionAlimtalkListResponse) => {
      setListItems(assembleData(rs.content));
    });
  };

  const callDownloadExcel = () => {
    let params: ExtensionAlimtalkDownloadExcelParams = {
      mid: mid,
      searchCl: searchCl,
      searchValue: searchValue,
      paymentMethod: paymentMethod,
      alimCl: alimCl,
      fromDate: fromDate,
      toDate: toDate,
      sendType: sendType,
      sendCl: sendCl
    };
    extensionAlimtalkDownloadExcel(params).then((rs: ExtensionAlimtalkDownloadExcelResponse) => {

    });
  };

  const assembleData = (content: Array<AlimtalkListContent>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let date = content[i]?.sendDate?.substring(0, 8);
        let groupDate = moment(date).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };

  const onClickToNavigate = () => {
    navigate(PATHS.additionalService.alimtalk.setting);
  };
  const onClickToDownloadExcel = () => {
    callDownloadExcel();
  };
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const getAlimtalkList = () => {
    let rs = [];
    if(Object.keys(listItems).length > 0){
      for (const [key, value] of Object.entries(listItems)) {
        rs.push(
          <ListDateGroup
            additionalServiceCategory={ AdditionalServiceCategory.Alimtalk }
            mid={ mid }
            key={ key }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  }
  
  useEffect(() => {
    callList();
  }, []);

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <section className="summary-section no-border">
              <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={ () => onClickToDownloadExcel() }
                >
                  <img 
                    src={ IMAGE_ROOT + '/ico_download.svg' }
                    alt="다운로드"
                  />
                </button>
              </div>
            </section>
              
            <section className="transaction-list">
            { getAlimtalkList() }
            </section>
          </div>
        </div>
      </main>
      <div className="apply-row">
        <button 
          className="btn-50 btn-blue flex-1"
          onClick={ () => onClickToNavigate() }
        >서비스 설정</button>
      </div>
    </>
  );
};