"use client";

import { useState, type InputHTMLAttributes } from "react";
import { MaterialIcon } from "../icons/nav-icons";

const inputClassName =
  "text-m-regular h-10 w-full rounded-lg border border-neutral-40 bg-neutral-10 px-[22px] py-2 text-neutral-100 placeholder:text-neutral-70 outline-none focus:border-primary-500 disabled:cursor-not-allowed disabled:opacity-60";

export type FormInputProps = Omit<
  InputHTMLAttributes<HTMLInputElement>,
  "id" | "value" | "onChange" | "className" | "type"
> & {
  id: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  helperText?: string;
  type?: InputHTMLAttributes<HTMLInputElement>["type"];
  withPasswordToggle?: boolean;
};

export function FormInput({
  id,
  label,
  value,
  onChange,
  helperText,
  disabled,
  type = "text",
  withPasswordToggle = false,
  ...inputProps
}: FormInputProps) {
  const [showPassword, setShowPassword] = useState(false);
  const inputType = withPasswordToggle
    ? showPassword
      ? "text"
      : "password"
    : type;

  return (
    <div className="flex flex-col gap-2">
      <label htmlFor={id} className="text-m-medium text-neutral-100">
        {label}
      </label>
      <div className={withPasswordToggle ? "relative" : undefined}>
        <input
          id={id}
          type={inputType}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          disabled={disabled}
          className={`${inputClassName} ${withPasswordToggle ? "pr-12" : ""}`}
          {...inputProps}
        />
        {withPasswordToggle && (
          <button
            type="button"
            onClick={() => setShowPassword((prev) => !prev)}
            className="absolute top-1/2 right-[22px] -translate-y-1/2 text-neutral-100"
            aria-label={
              showPassword ? "Sembunyikan password" : "Tampilkan password"
            }
            disabled={disabled}
          >
            <MaterialIcon
              name={showPassword ? "visibility" : "visibility_off"}
              size={20}
            />
          </button>
        )}
      </div>
      {helperText && (
        <p className="text-s-regular text-neutral-80">{helperText}</p>
      )}
    </div>
  );
}
