import { useState, useId, forwardRef } from "react";
import "./CInput.css";
import { FiEye, FiEyeOff } from "react-icons/fi";
import type { CInputProps } from "./CInput.types";

const CInput = forwardRef<HTMLInputElement, CInputProps>(
  (
    {
      label,
      placeholder,
      type = "text",
      disabled,
      error,
      style,
      className,
      ...rest
    },
    ref
  ) => {
    const [showPassword, setShowPassword] = useState(false);
    const isPassword = type === "password";
    const inputId = useId();

    return (
      <div className={`cinput-wrapper ${className || ""}`} style={style}>
        {label && (
          <label className="cinput-label" htmlFor={inputId}>
            {label}
          </label>
        )}
        <div className="cinput-inner">
          <input
            id={inputId}
            className={`cinput ${error ? "cinput-error" : ""}`}
            type={isPassword && showPassword ? "text" : type}
            placeholder={placeholder}
            disabled={disabled}
            autoComplete="off"
            ref={ref}
            {...rest}
          />
          {isPassword && (
            <span
              className="cinput-icon"
              onClick={() => setShowPassword((prev) => !prev)}
            >
              {showPassword ? <FiEyeOff /> : <FiEye />}
            </span>
          )}
        </div>
        {error && <span className="cinput-error-msg">{error}</span>}
      </div>
    );
  }
);

export default CInput;
