import React, { useState } from "react";
import { OSButton } from "../button/OSButton";

export interface ToggleButtonChangeEvent {
  value: boolean;
  originalEvent: null;
}

interface CustomToggleButtonProps {
  checked?: boolean;
  onChange?: (e: ToggleButtonChangeEvent) => void;
  className?: string;
  disabled?: boolean;
  onLabel?: string;
  /**
   * Style when true, Tailwind shorthand e.g bg-(--os-accent)
   */
  onStyle?: string;
  offLabel?: string;
  /**
   * Style when false, Tailwind shorthand e.g bg-(--os-accent)
   */
  offStyle?: string;
}

const CustomToggleButton: React.FC<CustomToggleButtonProps> = ({
  checked = false,
  onChange,
  className = "",
  disabled = false,
  onLabel = "ON",
  offLabel = "OFF",
  onStyle = "bg-(--os-accent) border-(--os-accent)",
  offStyle = "bg-(--danger-red)! border-(--cool-grey)",
}) => {
  const [isChecked, setIsChecked] = useState(checked);

  const handleToggle = () => {
    if (disabled) return;

    const newValue = !isChecked;
    setIsChecked(newValue);

    if (onChange) {
      onChange({
        value: newValue,
        originalEvent: null,
      });
    }
  };

  const buttonClasses = `
    m-0!
    inline-flex items-center justify-center
    px-2 py-2
    w-min
    transition-all duration-200 ease-in-out
    select-none
    text-white!
    ${disabled ? "opacity-60 cursor-not-allowed" : "cursor-pointer"}
    ${isChecked ? onStyle : offStyle}
    border
    ${className}
  `;

  return (
    <OSButton
      style={{ fontFamily: "Poppins"}}
      className={buttonClasses}
      onClick={handleToggle}
      disabled={disabled}
      aria-pressed={isChecked}
      label={isChecked ? onLabel : offLabel}
    />
  );
};

export default CustomToggleButton;
