import { SafeInput, Skeleton } from "@src/components";
import { NUMBER_INPUT_REGEX } from "@src/constants";
import { useSwapContext } from "@src/context";
import { useMemo } from "react";
import { SwapPanelType } from "../../../SwapView";
import { Balance } from "./Balance";
import { Ecosystem } from "@src/models";

type Props = {
  type: SwapPanelType;
};

export const AmountPanel = ({ type }: Props) => {
  const {
    srcChain,
    srcValue,
    srcValueUsd,
    dstToken,
    dstChain,
    dstValue,
    dstValueUsd,
    setSrcValue,
    isFetchingRoute,
    bridgeUI,
  } = useSwapContext();

  const value = useMemo(() => {
    if (
      type === "destination" &&
      dstToken &&
      dstChain &&
      bridgeUI &&
      srcChain?.ecosystem === Ecosystem.SOLANA
    ) {
      return srcValue;
    }
    return type === "source" ? srcValue : dstValue;
  }, [
    type,
    bridgeUI,
    srcChain?.ecosystem,
    srcValue,
    dstValue,
    dstToken,
    dstChain,
  ]);

  const valueUsd = useMemo(
    () => (type === "source" ? srcValueUsd : dstValueUsd),
    [dstValueUsd, 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 text-left">
        {type === "source" ? (
          <>
            <SafeInput
              id="swap-amount-input"
              className={`bg-transparent border-none p-0 text-xl outline-0 font-sans-bold font-bold`}
              regex={NUMBER_INPUT_REGEX}
              value={srcValue}
              onChange={(value) => setSrcValue(value)}
            />
            {valueUsd && (
              <div className={`text-sx opacity-60`}>{`$${valueUsd}`}</div>
            )}
          </>
        ) : isFetchingRoute ? (
          <div className="flex flex-col gap-1">
            <Skeleton className="w-[150px] h-[30px]" />
            <Skeleton className="w-[100px] h-[20px]" />
          </div>
        ) : (
          <>
            <div
              className={`text-xl text-t_text_secondary font-sans-bold font-bold`}
            >
              {value || 0}
            </div>
            {valueUsd && (
              <div className={`text-sx opacity-60`}>{`$${valueUsd}`}</div>
            )}
          </>
        )}
      </div>
      {type === "source" && <Balance />}
    </div>
  );
};
