import { cn } from "@/utils/cn";
import { createSignal, type JSX } from "solid-js";
import { EyeClosed } from "@icons/EyeClosed";
import { Eye } from "@icons/Eye";

type FormInput = (
  | JSX.InputHTMLAttributes<HTMLInputElement>
  | JSX.TextareaHTMLAttributes<HTMLTextAreaElement>
) & {
  label?: string;
  className?: string;
  error?: string;
  hint?: JSX.Element;
  setValue?: (val: JSX.InputHTMLAttributes<HTMLInputElement>["value"]) => void;
  multiLine?: boolean;
  grow?: boolean;
};
export const FormGroup = ({
  name,
  label,
  setValue,
  className,
  value,
  error,
  hint,
  multiLine,
  grow,
  ...rest
}: FormInput) => {
  const [showPassword, setShowPassword] = createSignal(
    rest.type !== "password"
  );
  return (
    <div class={`grid input-wrapper`}>
      <label for={name ?? undefined} class="px-2">
        <small>{label}</small>
      </label>

      <div
        class={cn([
          "flex min-h-12 rounded-lg border border-blue-900/5 outline-0 overflow-clip items-center",
          className,
        ])}
      >
        {multiLine ? (
          <textarea
            name={name ?? ""}
            onChange={(e) => setValue?.(e.currentTarget.value)}
            value={value ?? ""}
            {...rest}
            class="grow px-3 py-2 outline-none bottom-none"
          >
            {value}
          </textarea>
        ) : (
          <>
            {" "}
            <input
              name={name ?? ""}
              onInput={(e) => setValue?.(e.currentTarget.value)}
              value={value ?? ""}
              {...rest}
              type={
                showPassword() && rest.type === "password" ? "text" : rest.type
              }
              class="grow px-3 py-2 outline-none bottom-none"
            />
            {rest.type === "password" && (
              <span
                role="button"
                onClick={() => setShowPassword((prev) => !prev)}
                class="grid place-content-center mr-2"
              >
                {showPassword() ? (
                  <EyeClosed className="aspect-square w-4" />
                ) : (
                  <Eye className="aspect-square w-4" />
                )}
              </span>
            )}
          </>
        )}
      </div>

      <small class="px-2 grid transition-all duration-300">
        {hint}
        <span class="text-red-700 transition-all duration-300">{error}</span>
      </small>
    </div>
  );
};
