<script>import CloseIcon from "@requestnetwork/shared-icons/close.svelte";
import CopyIcon from "@requestnetwork/shared-icons/copy-icon.svelte";
import ExchangeIcon from "@requestnetwork/shared-icons/exchange.svelte";
import InfoCircleIcon from "@requestnetwork/shared-icons/info-circle.svelte";
import { onDestroy, onMount } from "svelte";
import { chains } from "../utils/chains";
import { NETWORK_LABEL } from "../utils/currencies";
import {
  handleRequestPayment,
  prepareRequestParameters
} from "../utils/request";
import Spinner from "./spinner.svelte";
import WalletInfo from "./wallet-info.svelte";
export let selectedCurrency;
export let amountInUSD;
export let sellerName;
export let productName;
export let sellerAddress;
export let currentPaymentStep;
export let web3Modal;
export let isConnected;
export let builderId;
export let persistRequest;
export let onPaymentSuccess;
export let onPaymentError;
const COUNTDOWN_INTERVAL = 30;
let amountInCrypto = 0;
let countdown = COUNTDOWN_INTERVAL;
let intervalId;
let exchangeRate = 0;
let error = "";
$:
  isLoadingPrice = true;
$:
  isPaying = false;
const currencySymbol = selectedCurrency.symbol.includes(
  selectedCurrency.network
) ? selectedCurrency.symbol.split("-")[0] : selectedCurrency.symbol;
async function fetchExchangeRate() {
  if (isPaying)
    return;
  try {
    isLoadingPrice = true;
    const response = await fetch(
      `https://api.coinbase.com/v2/exchange-rates?currency=USD`
    );
    const data = await response.json();
    let symbolCurrency = selectedCurrency.symbol.split("-")[0];
    const symbolMap = {
      fUSDC: "USDC",
      fUSDT: "USDT"
    };
    const lookupSymbol = symbolMap[symbolCurrency] || symbolCurrency;
    const rate = data.data.rates[lookupSymbol];
    exchangeRate = parseFloat(rate);
    amountInCrypto = amountInUSD * exchangeRate;
  } catch (error2) {
    alert("Unable to fetch exchange rate. Please try again later");
  } finally {
    isLoadingPrice = false;
  }
}
function startCountdown() {
  countdown = COUNTDOWN_INTERVAL;
  intervalId = setInterval(() => {
    countdown--;
    if (countdown === 0) {
      fetchExchangeRate();
      countdown = COUNTDOWN_INTERVAL;
    }
  }, 1e3);
}
$: {
  if (isPaying) {
    clearInterval(intervalId);
    countdown = 0;
  } else if (countdown === 0) {
    startCountdown();
  }
}
onMount(() => {
  fetchExchangeRate();
  startCountdown();
});
onDestroy(() => {
  clearInterval(intervalId);
});
function trimTrailingDecimalZeros(amount) {
  const stringAmount = amount.toString();
  const [wholePart, decimalPart] = stringAmount.split(".");
  if (!decimalPart) {
    return wholePart;
  }
  const trimmedDecimal = decimalPart.replace(/0+$/, "");
  return trimmedDecimal ? `${wholePart}.${trimmedDecimal}` : wholePart;
}
function getExplorerUrl(network, address) {
  const chain = chains.find(
    (chain2) => chain2.name.toLowerCase() === network.toLowerCase()
  );
  return chain ? `${chain.explorerUrl}/address/${address}` : "#";
}
</script>

<div class="payment-confirmation">
  <WalletInfo {web3Modal} bind:isConnected />
  <h3>Confirm Payment</h3>
  <div class="payment-confirmation-amount-info">
    <div>
      <div>USD</div>
      <span>${amountInUSD}</span>
    </div>
    <ExchangeIcon />
    <div>
      <div>{currencySymbol}</div>
      <span
        >{trimTrailingDecimalZeros(parseFloat(amountInCrypto.toFixed(6)))}
        {currencySymbol}</span
      >
    </div>
  </div>
  <div class="payment-confirmation-tab payment-confirmation-seller-address">
    <h4>Payment to</h4>
    <a
      href={getExplorerUrl(selectedCurrency.network, sellerAddress)}
      target="_blank"
    >
      <span>{sellerAddress}</span>
    </a>
    <button
      on:click={() => {
        navigator.clipboard.writeText(sellerAddress);
      }}
    >
      <CopyIcon />
    </button>
  </div>
  <div class="payment-confirmation-tab">
    <h4>Payment network</h4>
    <span>{NETWORK_LABEL[selectedCurrency.network]}</span>
  </div>
  <div class="payment-confirmation-tab">
    <h4>Total</h4>
    <span>{trimTrailingDecimalZeros(amountInCrypto)} {currencySymbol}</span>
  </div>

  {#if !isPaying}
    <div class="payment-confirmation-warning">
      <InfoCircleIcon />
      <div class="countdown" class:warning={countdown <= 10}>
        Price updates in {countdown}s
      </div>
    </div>
  {/if}

  {#if error && error.length > 0}
    <div class="payment-confirmation-error">
      <CloseIcon />

      <div class="error-message">
        {error}
      </div>
    </div>
  {/if}

  <div class="button-group">
    <button
      on:click={() => {
        currentPaymentStep = "currency";
      }}
      disabled={isPaying}
      class="btn btn-secondary">Back</button
    >
    <button
      class="btn"
      disabled={isLoadingPrice || !web3Modal || isPaying}
      on:click={async () => {
        isPaying = true;
        if (!web3Modal) return;

        const walletProvider = web3Modal.getWalletProvider();
        const payerAddress = web3Modal.getAddress();

        if (!walletProvider || !payerAddress) return;

        try {
          const requestParameters = prepareRequestParameters({
            currency: selectedCurrency,
            productName,
            sellerName,
            sellerAddress,
            payerAddress,
            amountInCrypto,
            exchangeRate,
            amountInUSD,
            builderId,
            createdWith: window.location.hostname,
          });

          const request = await handleRequestPayment({
            requestParameters,
            walletProvider,
            payerAddress: payerAddress,
            persistRequest,
          });

          if (onPaymentSuccess) {
            onPaymentSuccess(request);
          }

          currentPaymentStep = "complete";
        } catch (err) {
          if (err instanceof Error) {
            const errorMessage = err.message.includes("ACTION_REJECTED")
              ? "Payment process was rejected by the user"
              : err.message;
            if (onPaymentError) {
              onPaymentError(errorMessage);
            }

            error = errorMessage;
          }
        }

        isPaying = false;
      }}
    >
      {#if isPaying}
        <Spinner size="small" color="white" />
        <span>Processing payment...</span>
      {:else}
        <span>Pay</span>
      {/if}
    </button>
  </div>
</div>

<style>@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@100;200;300;400;500;600;700;800;900&display=swap");
body {
  font-family: "Montserrat", sans-serif;
}
h3 {
  margin: 0 0 15px;
  font-size: 18px;
  font-weight: bold;
}
.payment-confirmation {
  display: flex;
  flex-direction: column;
  width: 100%;
  gap: 16px;
}
.payment-confirmation .payment-confirmation-seller-address {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
}
.payment-confirmation .payment-confirmation-seller-address button {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.payment-confirmation-amount-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}
.payment-confirmation-amount-info > div {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}
.payment-confirmation-amount-info > div > div {
  width: 54px;
  height: 54px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  font-weight: bold;
  padding: 4px;
  font-size: 14px;
}
.payment-confirmation-amount-info > div span {
  font-weight: bold;
}
.payment-confirmation-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid #e0e0e0;
}
.payment-confirmation-tab > h4 {
  color: #666;
  font-size: 16px;
  font-weight: bold;
}
.payment-confirmation-tab > span {
  color: black;
  font-weight: 500;
  font-size: 14px;
}
.payment-confirmation-warning {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  color: black;
  background-color: #f5f5f5;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}
.payment-confirmation .countdown {
  color: black;
}
.payment-confirmation .countdown.warning {
  color: #ff4136;
  animation: blink 1s infinite;
}
.payment-confirmation .button-group {
  width: 100%;
  display: flex;
  gap: 10px;
}
.payment-confirmation .button-group .btn {
  display: inline-flex;
  cursor: pointer;
  color: white;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  background-color: #0bb489;
  border: none;
  outline: none;
  width: 100%;
  padding: 8px 16px;
  gap: 8px;
}
.payment-confirmation .button-group .btn:hover {
  background-color: rgba(11, 180, 137, 0.8);
}
.payment-confirmation .button-group .btn-secondary {
  background-color: #666;
}
.payment-confirmation .button-group .btn-secondary:hover {
  background-color: rgba(102, 102, 102, 0.8);
}
.payment-confirmation-error {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 12px;
  color: black;
  background-color: #f5f5f5;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}
.error-message {
  color: red;
}
@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}</style>
