import { forwardRef } from "react";

/**
 * Toggle (switch)
 *
 * variant:       "secondary" | "accent" | "info" | "success" | "warning" | "danger" | "neutral" | (default)
 * small:         boolean - smaller size
 * label:         string | ReactNode - label text
 * labelPosition: "start" | "end" (default: "start")
 * icon:          boolean - icon mode (renders span wrapper with two icon slots)
 * offIcon:       ReactNode - icon shown in the OFF state slot (icon mode only)
 * onIcon:        ReactNode - icon shown in the ON state slot (icon mode only)
 * indeterminate: boolean - sets indeterminate state imperatively
 */
const Toggle = forwardRef(function Toggle(
  {
    variant,
    small = false,
    label,
    labelPosition = "start",
    icon = false,
    offIcon,
    onIcon,
    indeterminate = false,
    className = "",
    ...props
  },
  ref
) {
  const toggleClasses = [
    "prs-toggle",
    variant && variant !== "default" && `prs-toggle-${variant}`,
    small && "prs-toggle-sm",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  const setRef = (el) => {
    if (el) el.indeterminate = indeterminate;
    if (typeof ref === "function") ref(el);
    else if (ref) ref.current = el;
  };

  const inputEl = icon ? (
    <span className={toggleClasses}>
      <input type="checkbox" ref={setRef} role="switch" {...props} />
      <span aria-hidden="true">{offIcon}</span>
      <span aria-hidden="true">{onIcon}</span>
    </span>
  ) : (
    <input
      type="checkbox"
      ref={setRef}
      className={toggleClasses}
      role="switch"
      {...props}
    />
  );

  if (!label) return inputEl;

  return (
    <label className="prs-toggle-label">
      {labelPosition === "start" && (
        <span className="prs-label-text">{label}</span>
      )}
      {inputEl}
      {labelPosition === "end" && (
        <span className="prs-label-text">{label}</span>
      )}
    </label>
  );
});

export default Toggle;
