// File: src/components/UIX/Toggle/Toggle.jsx
// Toggle Component - Theme-aware Toggle Switch

import React, { memo, useMemo, useCallback } from "react";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";

/**
 * Toggle Component
 * A theme-aware toggle switch for boolean values
 *
 * @param {boolean} checked - Current checked state
 * @param {Function} onChange - Change handler
 * @param {string} label - Optional label text
 * @param {boolean} disabled - Disabled state
 * @param {string} className - Additional CSS classes
 * @param {string} id - Input ID for accessibility
 * @param {string} name - Input name
 */
const Toggle = memo(
  ({
    checked = false,
    onChange,
    label,
    disabled = false,
    className = "",
    id,
    name,
    ...props
  }) => {
    const { getThemeClasses } = useUIXTheme();

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        bgMuted: getThemeClasses("bg-muted"),
        bgPrimary: getThemeClasses("bg-primary"),
        ringAccent: getThemeClasses("peer-focus:ring-accent"),
        border: getThemeClasses("after:border"),
      }),
      [getThemeClasses]
    );

    // Memoize change handler
    const handleChange = useCallback(
      (e) => {
        if (!disabled && onChange) {
          onChange(e);
        }
      },
      [disabled, onChange]
    );

    // Memoize toggle classes
    const toggleClasses = useMemo(
      () =>
        `w-11 h-6 ${themeClasses.bgMuted} peer-focus:outline-none peer-focus:ring-4 ${themeClasses.ringAccent} rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white ${themeClasses.border} after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:${themeClasses.bgPrimary} ${disabled ? "opacity-50 cursor-not-allowed" : ""}`.trim(),
      [themeClasses, disabled]
    );

    // Memoize container classes
    const containerClasses = useMemo(
      () => `relative inline-flex items-center ${disabled ? "cursor-not-allowed" : "cursor-pointer"} ${className}`.trim(),
      [disabled, className]
    );

    return (
      <label className={containerClasses}>
        <input
          type="checkbox"
          id={id}
          name={name}
          checked={checked}
          onChange={handleChange}
          disabled={disabled}
          className="sr-only peer"
          {...props}
        />
        <div className={toggleClasses}></div>
        {label && (
          <span className={`ml-3 text-sm font-medium ${disabled ? "opacity-50" : ""}`}>
            {label}
          </span>
        )}
      </label>
    );
  }
);

Toggle.displayName = "Toggle";

export default Toggle;
