import { twJoin } from "tailwind-merge";

import type { InputProps } from "./Input";

const gapMapping = {
  4: "gap-4",
  6: "gap-6",
  8: "gap-8",
};

export function useInputStyles({
  variant,
  height,
  disabled,
  error,
  gap,
}: Pick<InputProps, "variant" | "height" | "disabled" | "error"> & {
  gap?: 4 | 6 | 8;
}) {
  let bg = "bg-N0";
  if (disabled) {
    bg = "bg-N20A";
  } else if (variant === "secondary" && !error) {
    bg = "bg-N20A hover:bg-N0 focus-within:bg-N0";
  }

  let outlineColor = "outline-transparent";
  if (error) {
    outlineColor = "outline-R200";
  } else if (disabled) {
    if (variant === "outlined") {
      outlineColor = "outline-N40";
    }
  } else {
    if (variant === "outlined") {
      outlineColor = "outline-N40";
    }

    outlineColor = twJoin(
      outlineColor,
      "hover:outline-N40",
      "focus-within:outline-B200 hover:focus-within:outline-B200",
      "[&.Mui-focused]:outline-B200"
    );
  }

  let ring: string | null = null;
  if (error) {
    ring = "ring-3 ring-R400ER";
  } else if (!disabled) {
    ring = twJoin(
      "hover:ring-3 hover:ring-N900HR",
      "focus-within:ring-3 focus-within:ring-B400FR hover:focus-within:ring-B400FR",
      "[&.Mui-focused]:ring-B400FR"
    );
  }

  const classes = {
    root: twJoin(
      "group rounded-6",
      bg,
      disabled ? "text-N60" : "text-N100",
      "outline-1 outline -outline-offset-1",
      outlineColor,
      ring,
      gap ? gapMapping[gap] : height === "40" ? "gap-8" : "gap-4",
      "before:hidden after:hidden"
    ),
    input: twJoin(
      "h-auto overflow-hidden overflow-ellipsis whitespace-nowrap text-N700 text-style-R200",
      "placeholder:text-style-R200 placeholder:opacity-100",
      "autofill:transition-shadow autofill:duration-200 autofill:shadow-no-chrome-autofill group-hover:autofill:shadow-N0 focus:autofill:shadow-N0",
      disabled
        ? "autofill:shadow-N20A"
        : variant === "outlined"
        ? "autofill:shadow-N0"
        : "autofill:shadow-N20",
      disabled
        ? "[-webkit-text-fill-color:inherit] placeholder:text-N60"
        : "placeholder:text-N100",
      "hover:border-N40",
      "[&::-webkit-search-cancel-button]:hidden",
      height === "40" ? "py-10 px-12" : "py-6 px-8"
    ),
    adornedStart: height === "40" ? "pl-12" : "pl-8",
    adornedEnd: height === "40" ? "pr-12" : "pr-8",
    inputAdornedStart: "pl-0",
    inputAdornedEnd: "pr-0",
    ...(variant === "outlined" ? { notchedOutline: "hidden" } : {}),
  };

  return classes;
}
