import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { useCashReceiptDetailMutation } from '@/entities/transaction/api/use-cash-receipt-detail-mutation';
import { IssueInfoSection } from '@/entities/transaction/ui/section/issue-info-section';
import { DetailInfoSection } from '@/entities/transaction/ui/section/detail-info-section';
import { HeaderType } from '@/entities/common/model/types';
import { 
  TransactionCategory,
  CashReceiptDetailParams,
  DetailResponse,
  IssueInfo,
  DetailInfo,
  InfoSectionKeys,
  CashReceiptPurposeType,
  AmountInfo,
  CashReceiptPurposeUpdateParams,
  CashReceiptTransactionType
} from '@/entities/transaction/model/types';
import {
  useSetOnBack, 
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { CashReceitPurposeUpdateBottomSheet } from '@/entities/transaction/ui/cash-receit-purpose-update-bottom-sheet';
import { useCashReceiptPurposeUpdateMutation } from '@/entities/transaction/api/use-cash-receipt-purpose-update-mutation';
import { AmountInfoSection } from '@/entities/transaction/ui/section/amount-info-section';
import { snackBar } from '@/shared/lib';

export const CashReceiptDetailPage = () => {
  const { navigate, reload } = useNavigate();
  const { t } = useTranslation();
  const location = useLocation();
  
  const [amountInfo, setAmountInfo] = useState<AmountInfo>();
  const [issueInfo, setIssueInfo] = useState<IssueInfo>();
  const [detailInfo, setDetailInfo] = useState<DetailInfo>();
  const [showAmountInfo, setShowAmountInfo] = useState<boolean>(false);
  const [showDetailInfo, setShowDetailInfo] = useState<boolean>(false);
  const [bottomSheetOn, setBottomSheetOn] = useState<boolean>(false);
  const [purposeType, setPurposeType] = useState<string>();
  const [canDownloadReceipt, setCanDownloadReceipt] = useState<boolean>(false);


  useSetHeaderTitle(t('cashReceipt.detailTitle'));
  useSetHeaderType(HeaderType.RightClose);
  useSetOnBack(() => {
    navigate(PATHS.transaction.cashReceipt.list);
  });
  useSetFooterMode(false);

  const tid = location?.state.tid

  const { mutateAsync: cashReceiptDetail } = useCashReceiptDetailMutation();
  const { mutateAsync: cashReceiptPurposeUpdate } = useCashReceiptPurposeUpdateMutation();
  
  const callPurposeUpdate = () => {
    let newPurpose = (purposeType === CashReceiptPurposeType.EXPENSE_PROOF)
      ? CashReceiptPurposeType.INCOME_DEDUCTION: CashReceiptPurposeType.EXPENSE_PROOF;
    let params: CashReceiptPurposeUpdateParams = {
      tid: tid,
      newPurpose: newPurpose
    };
    cashReceiptPurposeUpdate(params).then((rs) => {
      setPurposeType(rs.afterPurposeType);
      setBottomSheetOn(false);
      snackBar('용도 변경을 성공하였습니다.', function(){
        reload();
      }, 2000);
    });  
  };

  const callDetail = () => {
    let cashReceitDetailParams: CashReceiptDetailParams = {
      tid: tid
    };
    cashReceiptDetail(cashReceitDetailParams).then((rs: DetailResponse) => {
      if(rs.amountDetail){
        rs.amountDetail.customerName =  rs.customerName;
      }
      setAmountInfo(rs.amountDetail || {});
      setIssueInfo(rs.issueInfo || {});
      setDetailInfo(rs.detailInfo || {});
      setCanDownloadReceipt(rs.detailInfo?.canDownloadReceipt || false);
      if(rs.issueInfo){
        setPurposeType(rs.issueInfo.purpose);
      }
    });
  };
  useEffect(() => {
    callDetail();
  }, []);

  const onClickToOpenInfo = (infoSectionKey: InfoSectionKeys) => {
    if(infoSectionKey === InfoSectionKeys.Amount){
      setShowAmountInfo(!showAmountInfo);
    }
    else if(infoSectionKey === InfoSectionKeys.Detail){
      setShowDetailInfo(!showDetailInfo);
    }
  };

  const onClickToPurposeUpdate = () => {
    setBottomSheetOn(true);
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="option-list">
              <div className={ `txn-detail ${(detailInfo?.canDownloadReceipt)? 'pb-86': ''}` }>
                <AmountInfoSection
                  transactionCategory={ TransactionCategory.CashReceipt }
                  amountInfo={ amountInfo }
                  isOpen={ showAmountInfo }
                  onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  purposeType={ purposeType }
                  canDownloadReceipt={ canDownloadReceipt }
                ></AmountInfoSection>
                <div className="txn-divider"></div>
                <IssueInfoSection
                  transactionCategory={ TransactionCategory.CashReceipt }
                  issueInfo={ issueInfo }
                  purposeType={ purposeType }
                ></IssueInfoSection>
                <div className="txn-divider minus"></div>
                { !!detailInfo &&
                  <DetailInfoSection
                    transactionCategory={ TransactionCategory.CashReceipt }
                    detailInfo={ detailInfo }
                    isOpen={ showDetailInfo }
                    onClickToOpenInfo={ (infoSectionKey) => onClickToOpenInfo(infoSectionKey) }
                  ></DetailInfoSection>
                }
              </div>
            </div>
            { (issueInfo?.transactionType === CashReceiptTransactionType.APPROVAL) &&
              (issueInfo?.processResult === '발급완료') &&
              <div className="apply-row">
                <button
                  className="btn-50 btn-blue flex-1"
                  onClick={ () => onClickToPurposeUpdate() }
                >{ t('cashReceipt.changePurpose') }</button>
              </div>
            }
          </div>
        </div>
      </main>
      <CashReceitPurposeUpdateBottomSheet
        setBottomSheetOn={ setBottomSheetOn }
        bottomSheetOn={ bottomSheetOn }
        callPurposeUpdate={ callPurposeUpdate }
      ></CashReceitPurposeUpdateBottomSheet>
    </>
  );
};