import * as React from "react";

import { cn, makeCapitalize } from "@/lib/utils";

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
  errorMsg?: string;
  makePlacholderAsLabel?: boolean;
  capitalize?: boolean;
}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  (
    {
      className,
      type,
      errorMsg,
      value,
      makePlacholderAsLabel = false,
      capitalize = false,
      ...props
    },
    ref
  ) => {
    const myRef = React.useRef<HTMLInputElement | null>(null);

    const [placeholder, setplaceholder] = React.useState(
      props.placeholder || ""
    );
    const [trackFocus, setTrackFocus] = React.useState(false);

    React.useImperativeHandle(ref, () => myRef.current!);

    const handleChange = (event: any) => {
      const { value } = event.target;
      const capitalizedValue = capitalize ? makeCapitalize(value) : value;
      myRef.current!.value = capitalizedValue;
      if (props.onChange) {
        props.onChange(event);
      }
    };

    React.useEffect(() => {
      setTrackFocus(!!myRef.current?.value);
    }, [ref]);

    return (
      <div className="space-y-1 w-full">
        {makePlacholderAsLabel && (
          <div className="h-6">
            {trackFocus && (
              <label htmlFor="" className="text-sm">
                {placeholder}
              </label>
            )}
          </div>
        )}
        <input
          type={type}
          // {...(capitalize
          //   ? { value: makeCapitalize(myRef.current?.value!) }
          //   : { value: myRef.current?.value })}
          // value={
          //   capitalize
          //     ? makeCapitalize(myRef.current?.value!)
          //     : myRef.current?.value
          // }
          className={cn(
            "flex  w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-50",
            className
          )}
          ref={(node) => {
            myRef.current = node;
            if (typeof ref === "function") {
              ref(node);
            } else if (ref) {
              ref.current = node;
            }
          }}
          {...props}
          onChange={handleChange}
          onFocus={() => {
            makePlacholderAsLabel && setTrackFocus(true);
          }}
          onBlur={(e) => {
            console.log(e.target.value);

            if (makePlacholderAsLabel && e.target.value === "")
              setTrackFocus(false);
          }}
        />
        <p className="text-xs text-red-500">{errorMsg}</p>
      </div>
    );
  }
);
Input.displayName = "Input";

export { Input };
