"use client";

import {
  type ChangeEvent,
  type RefAttributes,
  useState,
  useEffect,
} from "react";
import classNames from "classnames/dedupe";
import type { DOMProps } from "../../types/dom";
import { VisuallyHidden } from "../VisuallyHidden";
import "./Switch.css";

export type SwitchElementType = HTMLLabelElement;

export interface SwitchProps
  extends DOMProps, RefAttributes<SwitchElementType> {
  /** Custom class name for setting specific CSS */
  className?: string;
  checked?: boolean;
  onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
  isDisabled?: boolean;
}

const Switch = ({ ref, ...props }: SwitchProps) => {
  const {
    checked = false,
    className,
    onChange,
    isDisabled = false,
    ...otherProps
  } = props;
  const [enabled, setEnabled] = useState<boolean>(checked);

  useEffect(() => {
    setEnabled(checked);
  }, [checked]);

  const classes = classNames(
    "mobius",
    "mobius-switch",
    {
      "mobius-switch--checked": enabled,
      "mobius-switch--disabled": isDisabled,
    },
    className,
  );

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setEnabled(!enabled);
    if (onChange) {
      onChange(event);
    }
  };

  return (
    <label ref={ref} className={classes}>
      <VisuallyHidden>
        <span>{enabled ? "On" : "Off"}</span>
      </VisuallyHidden>
      <input
        type="checkbox"
        role="switch"
        checked={enabled}
        onChange={handleChange}
        disabled={isDisabled}
        {...otherProps}
      />
      <span className="mobius-switch__slider"></span>
    </label>
  );
};

Switch.displayName = "Switch";
export { Switch };
