import { TextUtil } from "@greatness/util";
import { Controller, useFormContext } from "react-hook-form";

import createUseStyles from "../../theme/createUseStyles";
import { cn } from "../../util/cn";

const useStyles = createUseStyles({
  textField: {
    "& > input": {
      "-moz-box-shadow": "none",
      "-webkit-box-shadow": "none",
      appearance: "none",
      backgroundImage: "none",
      boxShadow: "none",
      minHeight: 40,
    },
    "& > label": {
      left: 10,
      top: -5,
      whiteSpace: "nowrap",
      width: "min-content",
    },
    minHeight: 42,
  },
});

export default function TextInput({
  className,
  label,
  name,
  type = "text",
  isDisabled = false,
  autoComplete,
}: {
  autoComplete?: string;
  className?: string;
  isDisabled?: boolean;
  label?: string;
  name: string;
  type?: "text" | "password" | "email" | "textarea";
}) {
  const classes = useStyles();
  const {
    watch,
    control,
  } = useFormContext();
  const currentValue = watch(name);

  return (
    <Controller
      name={name}
      control={control}
      defaultValue={currentValue ?? ""}
      render={({ field }) => (
        <div className={cn("flex flex-col flex-1 relative justify-center", classes.textField, className)}>
          {type === "textarea" ? (
            <textarea
              id={name}
              {...field}
              disabled={isDisabled}
              className="border-white text-white outline-none py-xs px-s bg-black"
              rows={4}
            />
          ) : (
            <input
              type={type}
              id={name}
              {...field}
              disabled={isDisabled}
              autoComplete={autoComplete}
              {...(name === "newPassword" && {
                autoComplete: "new-password",
              })}
              className="border-white text-white outline-none py-xs px-s bg-black"
            />
          )}
          <label htmlFor={name} className="absolute word-break-keep-all bg-black font-size-xxs py-0 px-s text-white">
            {TextUtil.isEmpty(label) ? "" : label}
          </label>
        </div>
      )}
    />
  );
}
