import { useEffect } from 'react';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { FilterSelect } from '@/shared/ui/filter/select';
import { FilterSelectInput } from '@/shared/ui/filter/select-input';
import { FilterCalendar } from '@/shared/ui/filter/calendar';
import { FilterButtonGroups } from '@/shared/ui/filter/button-groups';
import { FilterRangeAmount } from '@/shared/ui/filter/range-amount';
import {
  getAllTransactionMoidTidOptionsGroup,
  getAllTransactionStatusCode,
} from '@/entities/transaction/model/contant';
import {
  AllTransactionFilterProps,
  AllTransactionSearchCl,
  AllTransactionMoidTid
} from '../../model/types';
import {
  FilterMotionDuration,
  FilterMotionStyle,
  FilterMotionVariants
} from '@/entities/common/model/constant';
import { useStore } from '@/shared/model/store';
import { FilterSelectMid } from '@/shared/ui/filter/select-mid';

export const AllTransactionFilter = ({
  filterOn,
  setFilterOn,
  mid,
  fromDate,
  toDate,
  statusCode,
  serviceCode,
  minAmount,
  maxAmount,
  cardCode,
  bankCode,
  searchCl,
  searchValue,
  setMid,
  setMoid,
  setTid,
  setFromDate,
  setToDate,
  setStatusCode,
  setServiceCode,
  setMinAmount,
  setMaxAmount,
  setCardCode,
  setBankCode,
  setSearchCl,
  setSearchValue,
  serviceCodeOptions
}: AllTransactionFilterProps) => {
  const { t } = useTranslation();

  const [filterMid, setFilterMid] = useState<string>(mid);
  const [filterMoidTidType, setFilterMoidTidType] = useState<AllTransactionMoidTid>(AllTransactionMoidTid.MOID);
  const [filterMoidTidValue, setFilterMoidTidValue] = useState<string>('');
  const [filterFromDate, setFilterFromDate] = useState<string>(fromDate);
  const [filterToDate, setFilterToDate] = useState<string>(toDate);
  const [filterStatusCode, setFilterStatusCode] = useState<string>(statusCode);
  const [filterServiceCode, setFilterServiceCode] = useState<string>(serviceCode);
  const [filterMinAmount, setFilterMinAmount] = useState<number | undefined>(minAmount);
  const [filterMaxAmount, setFilterMaxAmount] = useState<number | undefined>(maxAmount);

  const [filterCardCode, setFilterCardCode] = useState<string | undefined>(cardCode);
  const [filterBankCode, setFilterBankCode] = useState<string | undefined>(bankCode);

  const [filterCardBankCode, setFilterCardBankCode] = useState<string>('');

  const [filterSearchCl, setFilterSearchCl] = useState<AllTransactionSearchCl | undefined>(searchCl);
  const [filterSearchValue, setFilterSearchValue] = useState<string | undefined>(searchValue);

  const [searchClOptionsGroup, setSearchClOptionsGroup] = useState<Array<Record<string, string>>>([]);

  const midOptions = useStore.getState().UserStore.selectOptionsMids;

  const [statusCodeBtns, setStatusCodeBtns] = useState<Array<Record<string, string>>>();

  const moidTidOptionsGroup = getAllTransactionMoidTidOptionsGroup(t);
  const allTransactionStatusCode = getAllTransactionStatusCode(t);

  const getLocalizedServiceCodeName = (name?: string): string => {
    if (!name) return '';

    const nameMap: Record<string, string> = {
      '전체': t('transaction.constants.all'),
      '신용카드': t('transaction.constants.creditCard'),
      '계좌이체': t('transaction.constants.accountTransfer'),
      '가상계좌': t('transaction.constants.virtualAccount'),
      '휴대폰': t('transaction.constants.mobilePayment'),
      '문화상품권': t('transaction.constants.cultureLand'),
      '(구)SSG머니': t('transaction.constants.ssgMoney'),
      'SSG은행계좌결제': t('transaction.constants.ssgBank'),
      '계좌간편결제': t('transaction.constants.accountSimpleTransfer'),
      '티머니페이': t('transaction.constants.tmoneyPay'),
    };

    return nameMap[name] || name;
  };

  const getLocalizedServiceCodeOptions = () => {
    if (!serviceCodeOptions) return [];

    return serviceCodeOptions.map(option => ({
      ...option,
      name: getLocalizedServiceCodeName(option.name)
    }));
  };

  const onClickToClose = () => {
    setFilterOn(false);
  };
  
  const setNewDate = (newDate: any) => {
    console.log(newDate)
  };

  const onClickToSetFilter = () => {
    setMid(filterMid);
    if(filterMoidTidType === AllTransactionMoidTid.MOID){
      setMoid(filterMoidTidValue);
      setTid('');
    }
    else if(filterMoidTidType === AllTransactionMoidTid.TID){
      setMoid('');
      setTid(filterMoidTidValue);
    }
    setFromDate(filterFromDate);
    setToDate(filterToDate);
    setStatusCode(filterStatusCode);

    setServiceCode(filterServiceCode);
    setMinAmount(filterMinAmount);
    setMaxAmount(filterMaxAmount);
    setBankCode(filterBankCode);
    setCardCode(filterCardCode);
    setSearchCl(filterSearchCl);
    setSearchValue(filterSearchValue);
    onClickToClose();
  };

  
  
  let setSearchClOptions = (value: string) => {
    let options = [];
    setFilterServiceCode(value);

    if(value === ''){

    }
    else if(value === '01'){
      options.push({name: t('filter.searchOptions.cardNumber'), value: AllTransactionSearchCl.CARD_NO});
      options.push({name: t('filter.searchOptions.approvalNumber'), value: AllTransactionSearchCl.CARD_APPROVAL_NO});
    }
    else if(value === '02'){
      options.push({name: t('filter.searchOptions.buyerName'), value: AllTransactionSearchCl.BANK_BUYER_NM});
    }
    else if(value === '03'){
      options.push({name: t('filter.searchOptions.virtualAccountNumber'), value: AllTransactionSearchCl.VACCT_NO});
      options.push({name: t('filter.searchOptions.depositorName'), value: AllTransactionSearchCl.VACCT_DEPOSIT_NM});
    }
    else if(value === '05'){
      options.push({name: t('filter.searchOptions.phoneNumber'), value: AllTransactionSearchCl.TEL_NO});
    }
    else if(value === '14'){
      options.push({name: t('filter.searchOptions.giftCardNumber'), value: AllTransactionSearchCl.SSGMONEY_GIFT_NO});
    }
    else if(value === '21'){
      options.push({name: t('filter.searchOptions.approvalNumber'), value: AllTransactionSearchCl.SSGBANK_APPROVAL_NO});
    }
    else if(value === '24'){
      options.push({name: t('filter.searchOptions.customerId'), value: AllTransactionSearchCl.CMSBANK_USER_ID});
    }
    else if(value === '26'){
      options.push({name: t('filter.searchOptions.culturelandId'), value: AllTransactionSearchCl.SSGBANK_APPROVAL_NO});
    }
    else if(value === '31'){
      options.push({name: t('filter.searchOptions.tmoneyCardNumber'), value: AllTransactionSearchCl.TMONEY_CARD_NO});
    }
    setSearchClOptionsGroup(options);

  };
  
  const onChangeServiceCode = (val: string) => {
    let list = allTransactionStatusCode.filter((value, index) => {
      return val === value.serviceCode;
    })[0]?.list;
    let btns = list?.map((value, index) => {
      return {
        name: value.name,
        value: value.code
      }
    });
    setStatusCodeBtns(btns);
    setSearchClOptions(val);
  };


  useEffect(() => {
    onChangeServiceCode(serviceCode);
    setFilterServiceCode(serviceCode);
  }, [serviceCode]);

  return (
    <>
      <motion.div 
        className="full-menu-modal" 
        initial="hidden"
        animate={ (filterOn)? 'visible': 'hidden' }
        variants={ FilterMotionVariants }
        transition={ FilterMotionDuration }
        style={ FilterMotionStyle }
      >
        <div className="full-menu-container">
          <div className="full-menu-header">
            <div className="full-menu-title center">{t('filter.filter')}</div>
            <div className="full-menu-actions">
              <button
                id="closeFullMenu"
                className="full-menu-close"
              >
                <img
                  src={ IMAGE_ROOT + '/ico_close.svg' }
                  alt={t('filter.close')}
                  onClick={ () => onClickToClose() }
                />
              </button>
            </div>
          </div>

          <div className="option-list pt-16 pb-86">
            <FilterSelectMid
              title={t('filter.merchant')}
              selectSetter={ setMid }
              showType={ 'GID' }
            ></FilterSelectMid>
            <FilterSelectInput
              title={t('filter.orderNumberTid')}
              selectValue={ filterMoidTidType }
              selectSetter={ setFilterMoidTidType }
              selectOptions={ moidTidOptionsGroup }
              inputValue={ filterMoidTidValue }
              inputSetter={ setFilterMoidTidValue }
            ></FilterSelectInput>
            <FilterCalendar
              title={t('filter.period')}
              startDate={ filterFromDate }
              endDate={ filterToDate }
              setStartDate={ setFilterFromDate }
              setEndDate={ setFilterToDate }
            ></FilterCalendar>

            <FilterButtonGroups
              title={t('filter.transactionStatus')}
              activeValue={ filterStatusCode }
              btnGroups={ statusCodeBtns }
              setter={ setFilterStatusCode }
            ></FilterButtonGroups>

            { serviceCodeOptions &&
            <FilterSelect
              title={t('filter.paymentMethod')}
              selectValue={ filterServiceCode }
              selectSetter={ onChangeServiceCode }
              selectOptions={ getLocalizedServiceCodeOptions() }
            ></FilterSelect>
            }

            <FilterRangeAmount
              title={t('filter.transactionAmount')}
              minAmount={ filterMinAmount }
              maxAmount={ filterMaxAmount }
              setMinAmount={ setFilterMinAmount }
              setMaxAmount={ setFilterMaxAmount }
            ></FilterRangeAmount>
            {/*
            <FilterSelect
              title='카드사/은행'
              selectValue={}
              selectSetter={}
              selectOptions={}
            ></FilterSelect>
            */}
            <FilterSelectInput
              title={t('filter.detailSearch')}
              selectValue={ filterSearchCl }
              selectSetter={ setFilterSearchCl }
              selectOptions={ searchClOptionsGroup }
              inputValue={ filterSearchValue }
              inputSetter={ setFilterSearchValue }
            ></FilterSelectInput>

          </div>
          <div className="apply-row">
            <button
              className="btn-50 btn-blue flex-1"
              onClick={ () => onClickToSetFilter() }
            >{t('filter.apply')}</button>
          </div>
        </div>
      </motion.div>
    </>
  );
};