<template>
  <!-- <earn-allowance-flex v-if="!allowanceFlex" style="z-index:-1">
  </earn-allowance-flex> -->
  <div class="row">
    <div class="col-12 p-0">
      <div class="card p-card">
        <div class="d-flex flex-row justify-content-between align-items-center">
          <h4 class="card-custom-title">
            {{ $t(i18nConst.earnFlexTitle) }}
          </h4>
          <crypto-selector @tokenSelected="onCurrentTokenChange"  style="display:none;"></crypto-selector>
        </div>
        <hr>
        <div class="row">
          <div class="col-3 d-flex justify-content-center">
            <div class="text-center">
              <p style="font-weight: bold;">{{ $t(i18nConst.earnDuration) }}</p>
              <p class="mb-0">{{ durationInDays }} {{ $t(i18nConst.earnDurationDays) }}</p>
            </div>
          </div>
          <div class="col-8 d-flex justify-content-center">
            <div class="text-center">
              <p style="font-weight: bold;">{{ $t(i18nConst.earnFlexPerformanceIndex) }}</p>
              <p class="mb-0">
              <table class="blueTable">
                <thead>
                  <tr>
                    <th>{{ $t(i18nConst.earnFlexPeriod) }}</th>
                    <th>{{ $t(i18nConst.earnFlexAvailable) }}</th>
                    <th>{{ $t(i18nConst.earnFlexInterest) }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>{{ $t(i18nConst.earnFlexDec) }} 2022</td>
                    <td>{{ $t(i18nConst.earnFlexJan) }} 2023</td>
                    <td>5.16%</td>
                  </tr>
                  <tr>
                      <td>{{ $t(i18nConst.earnFlexJan) }} 2023</td>
                      <td>{{ $t(i18nConst.earnFlexFev) }} 2023</td>
                      <td>4.92%</td>
                  </tr>
                  <tr>
                      <td>{{ $t(i18nConst.earnFlexFev) }} 2023</td>
                      <td>{{ $t(i18nConst.earnFlexMar) }} 2023</td>
                      <td>0%</td>
                  </tr>
                  <tr>
                      <td>{{ $t(i18nConst.earnFlexMar) }} 2023</td>
                      <td>{{ $t(i18nConst.earnFlexAvr) }} 2023</td>
                      <td>9.63%</td>
                  </tr>
                </tbody>
              </table>
              </p>
            </div>
          </div>
          <div class="col-3 d-flex justify-content-center" style="margin-top:15px">
            <div class="text-center">
              <p style="font-weight: bold;">{{ $t(i18nConst.earnFlexFirstMonthRevenue) }}</p>
              <p>{{ parseFloat(firstMonthInterest * 100).toFixed(2) }} % </p>
            </div>
          </div>
          <div class="col-8 d-flex justify-content-center" style="margin-top:15px">
            <div class="text-center">
              <p style="font-weight: bold;">{{ $t(i18nConst.earnMetadexPriceUSDC) }}</p>
              <!-- <p>1 USDC = {{ parseFloat(metadexPrice).toFixed(4) }} METADEX</p> -->
              <p>1 {{ currentToken?.symbol }} = {{ utilsWeb3.formatDisplayAmount(parseFloat(amountForOneCurrentToken).toFixed(4)) }} METADEX</p>
            </div>
          </div>
        </div>
        <hr>
        <div class="row">
          <div class="col-12">
            <div class="row">
              <div class="col-12 col-md-6">
                <div class="form-check form-switch">
                  <input v-model="hasPromocode" @change="setPromocode" class="form-check-input" type="checkbox"
                    id="switchPromocode">
                  <label class="form-check-label" for="switchPromocode">{{ $t(i18nConst.earnPromocode) }} ?</label>
                </div>
                <div v-if="hasPromocode" class="row">
                  <div class="col-12 d-flex card-bc-item justify-content-between">
                    <div class="row">
                      <div class="col-6 d-flex justify-content-between align-items-center">
                        <div class="row d-flex align-items-center">
                          <div class="col-12">
                            <span>{{ $t(i18nConst.earnPromocode) }}</span>
                            <svg v-if="promocodeOk" xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                              fill="currentColor" class="bi bi-check-circle success-icon" viewBox="0 0 16 16">
                              <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
                              <path
                                d="M10.97 4.97a.235.235 0 0 0-.02.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-1.071-1.05z" />
                            </svg>
                            <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                              class="bi bi-x-circle error-icon" viewBox="0 0 16 16">
                              <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
                              <path
                                d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z" />
                            </svg>
                          </div>
                          <div class="col-12">
                            <input maxlength="10" type="text" name="promocode" class="form-control"
                              placeholder="Your code here..." v-model="promocodeInput" @keypress="checkChar($event)"
                              @keyup="checkPromocode">
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-6">
                <div class="form-check form-switch">
                  <div class="mb-2">
                    <input v-model="hasProtection" @change="setProtected" class="form-check-input" type="checkbox"
                      id="switchProtected">
                    <label class="form-check-label" for="switchProtected">{{ $t(i18nConst.earnProtection) }} </label>
                  </div>
                  <p><small><b style="color: var(--blue-custom)">{{
                    $t(i18nConst.earnProtectionActiveInfoTitle)
                  }}</b></small> <small> {{ $t(i18nConst.earnProtectionActiveInfoDescription) }}</small></p>
                  <p><small><b style="color: var(--blue-custom)">{{
                    $t(i18nConst.earnProtectionDeactivatedInfoTitle)
                  }}</b></small> <small> {{ $t(i18nConst.earnProtectionDeactivatedInfoDescription) }}</small></p>
                </div>
              </div>
            </div>
            <hr>
            <div class="row d-flex justify-content-center mb-3">
              <div class="col-12 col-md-5">
                <div class="form-floating">
                  <input :class="inErrorInput" class="form-control" type="number" min="100" id="amountInput"
                    @keyup="validateInput" @keypress="checkNumber($event)" placeholder="USDC"
                    style="text-align: center;" v-model="inputAmount">
                  <label for="amountInput"><span class="px-2" style="opacity:0.6">{{
                    $t(i18nConst.earnFixAmountUSDC)
                  }} ({{ currentToken?.symbol }})</span></label>

                  <small class="in-error" v-if="inErrorInput && insufficientBalanceError">{{
                    $t(i18nConst.earnInsufficientBalanceError)
                  }}<br></small>

                  <small class="in-error" v-if="inErrorInput && minAmountError && currentToken?.symbol === 'USDC'">{{
                    $t(i18nConst.earnMinAmountUsdcError)
                  }} {{ Number(utilsWeb3.formatAmount(this.minAmountCampaignUSDC[this.type][this.version], this.web3)).toFixed(2) }}
                    USDC</small>
                  <!-- <small class="in-error" v-if="inErrorInput && minAmountError && currentToken?.symbol === 'MATIC'">
                    {{ $t(i18nConst.earnMinAmountUsdcError) }} {{ Number(utilsWeb3.formatDisplayAmountWithEthers(this.minAmountCampaignWMATIC[this.type][this.version], 18)).toFixed(2) }} MATIC
                  </small> -->

                </div>
              </div>
            </div>
            <hr>
            <div class="row d-flex justify-content-center mb-3">
              <div class="col-12 col-md-5">
                <div class="form-floating">
                  <input style="background-color: var(--grey-custom); text-align: center;" id="totalMetadexInput"
                    readonly="readonly" class="form-control" type="number" placeholder="METADEX"
                    :value="parseFloat(totalMetadexAmount).toFixed(4)">
                  <label for="totalMetadexInput"><span class="px-2" style="opacity:0.6">{{
                    $t(i18nConst.earnFixTotalMetadex)
                  }}</span></label>
                </div>
              </div>
            </div>
            <div class="row" v-if="allowanceFlex && !loadingInProgress && !actionInProgress">
              <button v-if="!actionInProgress && promocodeOk && !inErrorInput" id="submit-flex" type="button"
                class="btn btn-meta-1 w-100 mb-4" @click="createCampaign">{{
                  $t(i18nConst.earnSubmit)
                }}</button>
              <button v-else type="button" class="disabled btn btn-meta-1 w-100 mb-4">{{
                $t(i18nConst.earnSubmit)
              }}</button>
            </div>
            <div class="row" v-else-if="!allowanceFlex && !loadingInProgress && !actionInProgress">
              <button id="confirm-allowance-btn" type="button" @click="addAllowanceBuyMetadex"
                class="btn btn-meta-1 w-100 mb-4">{{ $t(i18nConst.earnAllowanceButton) }}</button>
            </div>
            <div class="row" v-else>
              <button id="confirm-buy-btn" type="button" class="btn btn-primary disabled w-100 mb-4">
                <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import i18nConstantes from "@/constantes/i18n.constantes.js";
import constantes from "@/constantes/constantes.js";
import liquidityPoolService from '@/services/liquidityPool.service.js';
import typeActions from "../../store/typeActions";
//import EarnAllowanceFlex from "./EarnAllowanceFlex.vue";
import { mapGetters } from "vuex";
import { ethers } from 'ethers';
import web3Utils from "../../utils/web3.utils";
import { Token } from '@uniswap/sdk-core';
import CryptoSelector from "../cryptoSelect/CryptoSelector.vue";
import toolsService from "@/services/tools.service.js";
import constantesService from "@/services/constantes.service.js";

export default {
  data() {
    return {
      i18nConst: i18nConstantes,
      constantes: constantes,
      utils: ethers.utils,
      utilsWeb3: web3Utils,

      durationInDays: 180,
      interestAPR: 0.1,
      firstMonthInterest: parseFloat(0.3768 / 12),
      hasPromocode: false,
      hasProtection: true,
      promocodeOk: true,
      interestAmount: 0,
      inputAmount: 0,
      totalMetadexAmount: 0,
      getPriceInProgress: false,
      inErrorInput: false,
      promocodeInput: 'XXXXXXXXXX',
      insufficientBalanceError: false,
      minAmountError: false,
      type: 'FLEX',
      version: 'STD',
      loadingInProgress: false,
    }
  },
  components: {
    //EarnAllowanceFlex,
    CryptoSelector
  },
  props: {
    reserveToken: String,
    governanceToken: String,
    metadexPrice: String,
    balanceUsdc: Number,
  },
  computed: {
    ...mapGetters("earn", [
      "allowance", 
      //"allowanceWmatic", 
      "actionInProgress", "minAmountCampaignUSDC", 
      //"minAmountCampaignWMATIC", 
      "allowanceAmount", 
      //"allowanceWmaticAmount"
    ]),
    ...mapGetters("global", [
      "web3", "balanceUsdcNotFormatted", 
      //"balanceMaticNotFormatted"
    ]),
    ...mapGetters("crypto", ["currentToken"]),
    allowanceFlex() {
      const TokenUsdc = new Token(constantesService.getConstanteNetwork("chainId"), constantesService.getConstanteNetwork("addressSmartContractUSDCToken"), 6, 'USDC', 'USD Coin');
      //const TokenWmatic = new Token(constantesService.getConstanteNetwork("chainId"), constantesService.getConstanteNetwork("addressSmartContractWMATICToken"), 18, 'WMATIC', 'WMATIC');
      const _allowance = this.allowance[this.type];
      //const _allowanceWmatic = this.allowanceWmatic[this.type];

      switch (this.currentToken.symbol) {
        case "USDC":
          if (!_allowance) {
            return false;
          } else {
            //console.log("myAllowance => ", this.allowanceAmount[this.type], Math.trunc(this.allowanceAmount[this.type]));
            // eslint-disable-next-line no-undef
            const myBigInt = BigInt(Math.trunc(this.allowanceAmount[this.type]));
            // eslint-disable-next-line no-undef
            const compareBigInt = BigInt(20000 * 10**TokenUsdc.decimals);
            //console.log("allowance => ", ethers.utils.parseUnits(myBigInt.toString(), TokenUsdc.decimals));
            return myBigInt > compareBigInt;
          }
        // case "MATIC":
        //   if (!_allowanceWmatic) {
        //     return false;
        //   } else {
        //     //console.log("myAllowance => ", this.allowanceWmaticAmount[this.type], Math.trunc(this.allowanceWmaticAmount[this.type]));
        //     // eslint-disable-next-line no-undef
        //     const myBigInt = BigInt(Math.trunc(this.allowanceWmaticAmount[this.type]));
        //     // eslint-disable-next-line no-undef
        //     const compareBigInt = BigInt(20000 * 10**TokenWmatic.decimals);
        //     //console.log("allowance => ", ethers.utils.parseUnits(myBigInt.toString(), TokenUsdc.decimals));
        //     return myBigInt > compareBigInt;
        //   }
        default:
          return false;
          
      }
    },
    totalInterestAmount() {
      return this.totalMetadexAmount * (this.firstMonthInterest + ((this.durationInDays / (365 / 12)) * (this.interestAPR / 12)));
    },
    amountForOneCurrentToken() {
      const amount = toolsService.getAmountMetadexForOneCurrentToken();
      //console.log("amount for 1 current token => ", amount);
      return amount;
    },
  },
  methods: {
    async addAllowanceBuyMetadex() {
      switch (this.currentToken.symbol) {
        case "USDC":
          await this.$store.dispatch(typeActions.addAllowanceEarn, { type: 'FLEX' });
          break;
        // case "MATIC":
        //   await this.$store.dispatch(typeActions.addAllowanceEarnWmatic, { type: 'FLEX' });
        //   break;
        default:
          break;
      }
    },
    setPromocode() {
      this.promocodeInput = '';
      this.promocodeOk = false;
      if (!this.hasPromocode) {
        this.promocodeInput = 'XXXXXXXXXX';
        this.promocodeOk = true;
      }
    },
    checkPromocode() {
      this.promocodeInput = this.promocodeInput.replace(/[^a-zA-Z1-9]/g, "");
      if (this.promocodeInput.length == 10) {
        this.promocodeOk = true;
      } else {
        this.promocodeOk = false;
      }
    },
    checkChar(evt) {
      evt = evt ? evt : window.event;
      var charCode = evt.which ? evt.which : evt.keyCode;
      if (charCode >= 48 && charCode <= 57) {
        return true;
      } else if (charCode >= 65 && charCode <= 90) {
        return true;
      } else if (charCode >= 97 && charCode <= 122) {
        return true;
      } else {
        evt.preventDefault();
      }
    },
    checkNumber(evt) {
      evt = evt ? evt : window.event;
      var charCode = evt.which ? evt.which : evt.keyCode;

      if (charCode >= 48 && charCode <= 57) {
        return true;
      } else if (charCode == 44 || charCode == 46) {
        return true;
      } else {
        evt.preventDefault();
      }
    },
    async validateInput() {
      this.inErrorInput = '';
      this.insufficientBalanceError = false;
      this.minAmountError = false;
      if (this.inputAmount !== '' && this.inputAmount > 0) {
        //const minAmountCampaignWMATIC = parseFloat(this.utilsWeb3.formatAmountWithEthers(this.minAmountCampaignWMATIC[this.type][this.version], 18));
        //console.log("minAmountCampaignWMATIC FLEX => ", minAmountCampaignWMATIC);

        switch (this.currentToken.symbol) {
          case "USDC":
            if (this.inputAmount > this.balanceUsdc) {
              this.inErrorInput = 'in-error';
              this.insufficientBalanceError = true;
            }
            if (this.inputAmount < Number(web3Utils.formatAmount(this.minAmountCampaignUSDC[this.type][this.version], this.web3)).toFixed(4)) {
              this.inErrorInput = 'in-error';
              this.minAmountError = true;
            }
            break;
          // case "MATIC":
          //   //console.log("validateInput MATIC => ", this.inputAmount, parseFloat(this.utilsWeb3.formatAmountWithEthers(this.balanceMaticNotFormatted, 18)), minAmountCampaignWMATIC);
          //   if (this.inputAmount > parseFloat(this.utilsWeb3.formatAmountWithEthers(this.balanceMaticNotFormatted, 18))) {
          //     //console.log("not enough balance wmatic");
          //     this.inErrorInput = 'in-error';
          //     this.insufficientBalanceError = true;
          //   }
          //   if (parseFloat(this.inputAmount) < minAmountCampaignWMATIC) {
          //     //console.log("amount less than min wmatic");
          //     this.inErrorInput = 'in-error';
          //     this.minAmountError = true;
          //   }
          //   break;
          default:
            break;
        }
      }
      await this.getEstimatedPrice();
    },
    async getEstimatedPrice() {
      if (this.inputAmount !== '' && this.inputAmount > 0) {
        this.getPriceInProgress = true;
        switch (this.currentToken.symbol) {
          case "USDC":
            this.totalMetadexAmount = await liquidityPoolService.getQuoteUsdcMetadex(String(this.inputAmount));    
            break;
          // case "MATIC":
          //   this.totalMetadexAmount = await liquidityPoolService.getQuoteMaticMetadex(String(this.inputAmount));
          //   break;
          default:
            break;
        }
        this.getPriceInProgress = false;
      } else {
        this.totalMetadexAmount = 0;
      }
    },
    async createCampaign() {
      switch (this.currentToken.symbol) {
        case "USDC":
          await this.$store.dispatch(typeActions.createCampaign, { amountUSDC: this.inputAmount, promocode: this.promocodeInput, protection: this.hasProtection, type: this.type, version: this.version });
          break;
        // case "MATIC":
        // await this.$store.dispatch(typeActions.createCampaignWMATIC, { amount: this.inputAmount, promocode: this.promocodeInput, protection: this.hasProtection, type: this.type, version: this.version });
        //   break;
        default:
          break;
      }
    },
    async getAllowanceCurrentToken() {
      switch (this.currentToken?.symbol) {
        case "USDC":
          await this.$store.dispatch(typeActions.getAllowanceEarn, { type: this.type });    
          break;
        // case "MATIC":
        //   await this.$store.dispatch(typeActions.getAllowanceEarnWmatic, { type: this.type });
        //   break;
        default:
          break;
      }
    },
    setMinAmountForCurrentToken() {
      //const _amount = parseFloat(this.utilsWeb3.formatAmountWithEthers(this.minAmountCampaignWMATIC[this.type][this.version], 18));
      
      switch (this.currentToken.symbol) {
        case "USDC":
          this.inputAmount = 100;
          break;
        // case "MATIC":
          
        //   this.inputAmount = Math.ceil(_amount * 100) / 100;
        //   break;
        default:
          break;
      }
      this.validateInput();
    },
    async onCurrentTokenChange() {
      this.setMinAmountForCurrentToken();
      this.getAllowanceCurrentToken();
      this.getEstimatedPrice();
    }
  },
  async mounted() {
    this.loadingInProgress = true;
    const tokenUsdc = new Token(constantesService.getConstanteNetwork("chainId"), constantesService.getConstanteNetwork("addressSmartContractUSDCToken"), 6, 'USDC', 'USD Coin');
    await this.$store.dispatch(typeActions.setCurrentToken, tokenUsdc);

    await this.$store.dispatch(typeActions.updateUsdcToMetadexPrice);
    //await this.$store.dispatch(typeActions.updateMaticToMetadexPrice);
    //await this.$store.dispatch(typeActions.getAllowanceEarn, { type: this.type });
    this.getAllowanceCurrentToken();
    await this.$store.dispatch(typeActions.getMinAmountCampaignUSDC, { type: this.type, version: this.version });
    //await this.$store.dispatch(typeActions.getMinAmountCampaignWMATIC, { type: this.type, version: this.version });
    this.setMinAmountForCurrentToken();
    await this.getEstimatedPrice();
    this.loadingInProgress = false;
  }
}
</script>

<style scoped>
.error {
  color: red;
  font-size: small;
}

.success-icon {
  padding-left: 0.3rem;
  color: green;
}

.error-icon {
  padding-left: 0.3rem;
  color: red;
}

table.blueTable {
  border: 1px solid #1C6EA4;
  background-color: #EEEEEE;
  width: 100%;
  text-align: left;
  border-collapse: collapse;
}

table.blueTable td,
table.blueTable th {
  border: 1px solid #AAAAAA;
  padding: 3px 2px;
}

table.blueTable tbody td {
  font-size: 13px;
  color: #000000;
}

table.blueTable tr:nth-child(even) {
  background: #D0E4F5;
}

table.blueTable thead {
  background: var(--blue-custom);
  border-bottom: 2px solid #444444;
}

table.blueTable thead th {
  font-size: 13px;
  color: #FFFFFF;
  border-left: 2px solid #D0E4F5;
}

table.blueTable thead th:first-child {
  border-left: none;
}
</style>