import { SafeInput } from "@src/components/SafeInput";
import { Skeleton } from "@src/components/Skeleton";
import { NUMBER_INPUT_REGEX } from "@src/constants";
import { useSwapContext } from "@src/context";
import { ADDRESSES } from "@src/contracts";
import { useDebounce, useShift4Api } from "@src/hooks";
import { useEffect } from "react";

type Props = {
  type: "destination" | "source";
};

export const AmountPanel = ({ type }: Props) => {
  const {
    dstValue,
    setSrcValue,
    isFetchingRoute,
    srcValueUsd,
    setSrcValueUsd,
    srcChain,
  } = useSwapContext();

  const { GetQuote } = useShift4Api();
  const { debounce: getQuoteDebounce } = useDebounce({
    delayMs: 600,
  });

  useEffect(() => {
    //calculate amount of native
    if (!srcValueUsd || type !== "source" || !srcChain) {
      return;
    }

    getQuoteDebounce(() => {
      GetQuote(
        {
          cryptoCurrencyCode: "ETH",
          fiatAmount: srcValueUsd,
          fiatCurrencyCode: "USD",
          walletAddress: ADDRESSES[srcChain.chainId]?.SwapperRouter || "", // todo fix
        },
        srcChain,
      ).then((response) => {
        if (response.data.quote.cryptoAmount) {
          setSrcValue(response.data.quote.cryptoAmount.toString());
        }
      });
    });
  }, [GetQuote, getQuoteDebounce, setSrcValue, srcChain, srcValueUsd, type]);

  return (
    <div className="flex justify-between items-center w-full p-4 gap-8 overflow-hidden">
      <div className="flex flex-col font-medium w-full overflow-hidden">
        {type === "source" ? (
          <div className="flex justify-between items-center">
            <SafeInput
              id="swap-amount-input"
              className={`bg-transparent border-none p-0 text-2xl placeholder:text-xl placeholder:lh placeholder:text-t_text_primary placeholder:text-opacity-60 outline-0 w-full`}
              regex={NUMBER_INPUT_REGEX}
              value={srcValueUsd}
              onChange={(value) => {
                setSrcValueUsd(value);
              }}
              placeholder="Type in $ amount"
            />
            <p className="text-2xl text-t_text_primary text-opacity-60">USD</p>
          </div>
        ) : isFetchingRoute ? (
          <div className="flex flex-col gap-1">
            <Skeleton className="w-[150px] h-[28px]" />
          </div>
        ) : (
          <>
            <div className={`text-xl text-t_text_secondary`}>
              {dstValue || 0}
            </div>
            <div className={`text-sx opacity-60`}>
              {/* {Number(valueUsd) ? `$${valueUsd}` : ""} */}
            </div>
          </>
        )}
      </div>
    </div>
  );
};
