/**
 * Toggle Component - ProRank SEO
 *
 * Premium toggle switch component for boolean settings.
 * Modern alternative to checkboxes for on/off states.
 *
 * @example
 * <Toggle label="Enable Feature" checked={enabled} onChange={setEnabled} />
 * <Toggle
 *   label="Advanced Mode"
 *   description="Enable advanced features"
 *   checked={advanced}
 *   onChange={setAdvanced}
 *   size="lg"
 * />
 */

import React from 'react';

// Size configurations
const sizeConfig = {
  sm: { track: { width: 46, height: 28 }, thumb: 22, padding: 3 },
  md: { track: { width: 56, height: 32 }, thumb: 24, padding: 4 },
  lg: { track: { width: 62, height: 36 }, thumb: 28, padding: 4 },
};

const Toggle = React.forwardRef(({
  label,
  description,
  helpText,
  id,
  name,
  checked = false,
  onChange,
  disabled = false,
  error,
  className = '',
  size = 'md',
  ...props
}, ref) => {
  const toggleId = id || name || `toggle-${Math.random().toString(36).substr(2, 9)}`;
  const hasError = Boolean(error);
  const config = sizeConfig[size] || sizeConfig.md;
  const helperDescription = description || helpText;

  // Handle toggle change
  const handleToggle = () => {
    if (!disabled && onChange) {
      onChange(!checked);
    }
  };

  // Handle keyboard events
  const handleKeyDown = (e) => {
    if (e.key === ' ' || e.key === 'Enter') {
      e.preventDefault();
      handleToggle();
    }
  };

  // Track styles (the pill-shaped background)
  const trackStyle = {
    position: 'relative',
    display: 'inline-flex',
    alignItems: 'center',
    width: config.track.width,
    height: config.track.height,
    borderRadius: 9999,
    background: checked
      ? 'linear-gradient(135deg, #ff8a1a 0%, #ff6900 58%, #e25b00 100%)'
      : 'linear-gradient(180deg, #dde4ee 0%, #c7d0dd 100%)',
    cursor: disabled ? 'not-allowed' : 'pointer',
    opacity: disabled ? 0.5 : 1,
    transition: 'all 0.2s ease',
    border: `1px solid ${checked ? 'rgba(255, 105, 0, 0.55)' : 'rgba(148, 163, 184, 0.55)'}`,
    padding: 0,
    outline: 'none',
    boxShadow: checked
      ? '0 0 0 4px rgba(255, 105, 0, 0.14), inset 0 1px 1px rgba(255, 255, 255, 0.18)'
      : 'inset 0 1px 1px rgba(255, 255, 255, 0.7), 0 1px 2px rgba(15, 23, 42, 0.08)',
  };

  // Thumb styles (the sliding circle)
  const thumbStyle = {
    position: 'absolute',
    top: config.padding,
    left: checked ? config.track.width - config.thumb - config.padding : config.padding,
    width: config.thumb,
    height: config.thumb,
    borderRadius: '50%',
    backgroundColor: '#ffffff',
    boxShadow: '0 3px 10px rgba(15, 23, 42, 0.22), 0 1px 2px rgba(15, 23, 42, 0.12)',
    transition: 'left 0.2s',
  };

  return (
    <div>
      <div
        className={className}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 16,
          opacity: disabled ? 0.5 : 1,
        }}
      >
        {/* Label and description */}
        {(label || helperDescription) && (
          <div
            style={{ flex: 1, cursor: disabled ? 'default' : 'pointer' }}
            onClick={!disabled ? handleToggle : undefined}
          >
            {label && (
              <span style={{
                display: 'block',
                fontSize: 14,
                fontWeight: 500,
                color: hasError ? '#b91c1c' : '#111827',
              }}>
                {label}
              </span>
            )}
            {helperDescription && (
              <span
                id={`${toggleId}-description`}
                style={{
                  display: 'block',
                  marginTop: 4,
                  fontSize: 12,
                  color: hasError ? '#dc2626' : '#6b7280',
                }}
              >
                {helperDescription}
              </span>
            )}
          </div>
        )}

        {/* Toggle switch */}
        <button
          ref={ref}
          id={toggleId}
          type="button"
          role="switch"
          aria-checked={checked}
          aria-invalid={hasError}
          aria-describedby={
            error ? `${toggleId}-error` : helperDescription ? `${toggleId}-description` : undefined
          }
          disabled={disabled}
          onClick={handleToggle}
          onKeyDown={handleKeyDown}
          style={trackStyle}
          {...props}
        >
          <span className="prorank-toggle-slider__thumb" style={thumbStyle} />
        </button>
      </div>

      {/* Error message */}
      {error && (
        <p
          id={`${toggleId}-error`}
          style={{
            marginTop: 8,
            fontSize: 12,
            color: '#dc2626',
          }}
          role="alert"
        >
          {error}
        </p>
      )}
    </div>
  );
});

Toggle.displayName = 'Toggle';

export default Toggle;
