import { cn } from "@/utils/class-merge";
import { forwardRef, HTMLProps, useEffect } from "preact/compat";
import { tv } from "tailwind-variants";
import classes from "./Input.module.scss";

const input = tv({
  base: classes.input_field,
  variants: {
    "text-align": {
      center: "text-center",
      left: "text-left",
    },
    "border-error": {
      true: "border-red-500 placeholder:text-red-500",
      false: "border-gray-300",
    },
  },
  defaultVariants: {
    "text-align": "left",
  },
});

interface InputProps extends HTMLProps<HTMLInputElement> {
  textAlign?: "center" | "left";
  error?: string;
}

const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  const { textAlign, error, type = "text", ...rest } = props;
  useEffect(() => {
    console.log(`error: ${error}`);
  }, [error]);
  return (
    <div class="flex w-full flex-col items-center gap-1">
      <input class={input({ "text-align": textAlign, "border-error": !!error })} ref={ref} type={type} {...rest} />
      <p
        class={cn("invisible h-10 w-[80%] text-center text-[0.7rem] break-words text-red-500", {
          visible: error !== "",
        })}
      >
        {error}
      </p>
    </div>
  );
});

Input.displayName = "AHInput";

export default Input;
