"use client";
import { EyeIcon, EyeSlashIcon } from "@phosphor-icons/react";
import { InputHTMLAttributes, forwardRef, useState } from "react";

import clsx from "clsx";

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  label?: string;
  error?: string;
}

export const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ label, error, id, className, type, ...props }, ref) => {
    const [showPassword, setShowPassword] = useState(false);
    const isPassword = type === "password";

    return (
      <div>
        {label && (
          <label
            htmlFor={id}
            className="block text-base font-semibold text-[#006f36] mb-3"
          >
            {label}
          </label>
        )}
        <div className="relative">
          <input
            ref={ref}
            id={id}
            type={isPassword && showPassword ? "text" : type}
            className={clsx(
              "block w-full border-2 border-[#e9e9e9] rounded-xl px-3 py-3 text-base bg-white text-black focus:border-[#006f36] focus:outline-none transition-colors",
              error && "border-red-500",
              isPassword && "pr-12",
              className
            )}
            {...props}
          />
          {isPassword && (
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-[#006f36] transition-colors"
            >
              {showPassword ? (
                <EyeSlashIcon size={24} weight="regular" />
              ) : (
                <EyeIcon size={24} weight="regular" />
              )}
            </button>
          )}
        </div>
        {error && (
          <p className="mt-1 text-sm text-red-600">{error}</p>
        )}
      </div>
    );
  }
);

Input.displayName = "Input";
