"use client";

import React, { useState } from "react";
import Image from "next/image";
import { FieldError } from "react-hook-form";

interface FormInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: FieldError | any;
  showPasswordToggle?: boolean;
  containerClassName?: string;
}

const FormInput = React.forwardRef<HTMLInputElement, FormInputProps>(
  (
    {
      label,
      error,
      type = "text",
      showPasswordToggle = false,
      containerClassName = "",
      className = "",
      id,
      ...props
    },
    ref
  ) => {
    const [showPassword, setShowPassword] = useState(false);

    const isPassword = type === "password" || (showPasswordToggle && type === "password");
    const inputType = showPasswordToggle && showPassword ? "text" : type;

    return (
      <div className={`w-full max-w-[399px] space-y-1 ${containerClassName}`}>
        <div
          className={`relative group flex items-center p-[16px] gap-[2px] rounded-[10px] border transition-all ${
            error ? "border-red-500" : "border-brand-border-alt"
          } focus-within:border-blue-light focus-within:border-[1.5px]`}
        >
          <label
            htmlFor={id}
            className={`absolute -top-[11px] left-[15px] bg-white px-[8px] text-[14px] font-semibold leading-[150%] font-sans transition-colors [font-feature-settings:'liga'_off,'clig'_off] ${
              error ? "text-red-500" : "text-blue-deep"
            } group-focus-within:text-blue-light`}
          >
            {label}
          </label>
          <input
            id={id}
            ref={ref}
            type={inputType}
            className={`w-full bg-transparent outline-none text-[16px] font-medium text-blue-deep font-sans placeholder:text-blue-deep/30 ${className}`}
            {...props}
          />
          {showPasswordToggle && (
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="text-blue-deep/40 hover:text-blue-deep ml-2 flex items-center justify-center cursor-pointer"
            >
              <Image
                src={`/assets/icons/${showPassword ? "eye-open.svg" : "eye-close.svg"}`}
                alt={showPassword ? "Hide" : "Show"}
                width={24}
                height={24}
                className="w-6 h-6 object-contain"
              />
            </button>
          )}
        </div>
        {error && (
          <p className="text-red-500 text-xs mt-1 pl-[16px] font-sans">
            {error.message}
          </p>
        )}
      </div>
    );
  }
);

FormInput.displayName = "FormInput";

export default FormInput;
