import React, { useState, ChangeEvent } from "react";
import { startCase } from "lodash-es";
import { Eye, EyeClosed } from "lucide-react";

interface Props {
  register: any;
  fieldName: string;
  fieldLabel?: string;
  type: string;
  moreCss?: string;
  required?: boolean;
  isValidated?: boolean;
  validateFn?: () => void;
  handleKeyDown?: () => void;
  onChangeFn?: (value: string) => void;
  defaultValue?: string;
  placeholder?: string | boolean;
  isDisabled?: boolean;
  tooltip?: string;
}

const TextInput: React.FC<Props> = ({
  register,
  fieldName,
  fieldLabel,
  type,
  moreCss = "border-stroke",
  required,
  isValidated,
  validateFn,
  handleKeyDown,
  onChangeFn,
  defaultValue,
  placeholder = true,
  isDisabled,
  tooltip,
}) => {
  const [password, setPassword] = useState<string>("password");

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    if (onChangeFn) {
      onChangeFn(e.target.value);
    }
  };

  const togglePasswordVisibility = () => {
    setPassword((prev) => (prev === "password" ? "text" : "password"));
  };

  return (
    <div className="relative w-full">
      <input
        id={fieldName}
        defaultValue={defaultValue}
        className={`
          ${
            type !== ("email" || "password") && "capitalize"
          } w-full rounded-md border-2 bg-transparent py-2.5 px-3 text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-white
          ${moreCss}`}
        type={type === "password" ? password : type}
        placeholder={
          placeholder
            ? typeof placeholder === "string"
              ? placeholder
              : `Enter ${
                  fieldLabel?.toLowerCase() ||
                  startCase(fieldName).toLowerCase()
                }...`
            : ""
        }
        {...register(fieldName, {
          required: required ? "This field is required." : false,
          validate: isValidated ? validateFn : undefined,
          onChange: handleChange,
        })}
        onKeyDown={handleKeyDown}
        disabled={isDisabled}
        autoComplete="on"
      />
      {type === "password" && (
        <span
          className="absolute right-4 bottom-3 text-2xl hover:cursor-pointer"
          onClick={togglePasswordVisibility}
          as="button"
        >
          {password === "password" ? <Eye /> : <EyeClosed />}
        </span>
      )}

      {tooltip && <span className="tooltip">{tooltip}</span>}
    </div>
  );
};

export default TextInput;
