import { SafeInput } from "@src/components";
import { NUMBER_INPUT_REGEX } from "@src/constants";
import { useSwapContext } from "@src/context";
import { useState } from "react";

export const Slippage = () => {
  const { slippage, setSlippage } = useSwapContext();
  const [customSlippage, setCustomSlippage] = useState(slippage);

  const onInputChange = (value: string) => {
    if (value.length === 0) {
      setCustomSlippage("");
      setSlippage(defaultPreset);
    } else {
      if (value.length >= 5) {
        value = value.substring(0, 5);
      }
      if (Number(value) <= 100) {
        setCustomSlippage(value);
        setSlippage(value);
      }
    }
  };

  const defaultPreset = "1.5";
  const presets = ["0.5", "1.5", "3.0"];
  return (
    <div className="flex flex-col gap-5 pt-5 border-t border-solid border-t_text_primary border-opacity-10">
      <h1 className="text-sm font-medium text-left">Slippage</h1>
      <div className="flex items-center gap-2 w-full">
        <div className="flex items-center bg-t_bg_tertiary bg-opacity-5 p-1 border border-solid border-t_text_primary border-opacity-10 rounded-xl gap-2">
          {presets.map((preset) => (
            <button
              key={preset}
              type="button"
              onClick={() => onInputChange(preset)}
              className={`block rounded-lg text-sm bg-transparent h-7 px-1 hover:bg-gradient-to-r hover:from-t_main_accent_light hover:to-t_main_accent_dark hover:opacity-100 ${
                slippage === preset
                  ? "gradient-slippage-container-blue text-white opacity-100"
                  : "text-t_text_primary opacity-20"
              }`}
            >
              {`${preset}%`}
            </button>
          ))}
        </div>
        <div
          className={`${
            customSlippage
              ? "gradient-slippage-container-blue p-[1px] rounded-xl"
              : ""
          }`}
        >
          <div
            className={`bg-t_bg_primary p-1 h-full border border-solid border-t_text_primary border-opacity-10 rounded-xl`}
          >
            <SafeInput
              id="slippage-input"
              placeholder="1.5"
              regex={NUMBER_INPUT_REGEX}
              value={customSlippage}
              onChange={onInputChange}
              className={`text-sm leading-none bg-transparent px-0.5 placeholder:text-t_text_primary/20 focus:outline-none ${
                customSlippage ? "text-t_text_primary" : "text-white"
              } `}
            />{" "}
            %
          </div>
        </div>
      </div>
      <div className="text-sm opacity-60">
        <p>
          Slippage is the price variation you are willing to accept in the event
          that the price of the trade changes while it is processing.
        </p>
        <br />
        <p>
          If the trade fails due to too low slippage, you will receive USDC on
          the destination chain.
        </p>
      </div>
    </div>
  );
};
