import { useState, useEffect } from '@wordpress/element';
import * as React from 'react';

/**
 * ProRank Toggle Slider Component
 * Settings toggle without text display
 * Used for individual feature toggles within settings
 */

interface ProrankToggleSliderProps {
  checked?: boolean;
  onChange?: (checked: boolean) => void;
  disabled?: boolean;
  className?: string;
  size?: 'small' | 'medium';
}

const ProrankToggleSlider: React.FC<ProrankToggleSliderProps> = ({
  checked = false,
  onChange,
  disabled = false,
  className = '',
  size = 'medium'
}) => {
  const [isChecked, setIsChecked] = useState(checked);

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

  const handleToggle = () => {
    if (!disabled) {
      const newValue = !isChecked;
      setIsChecked(newValue);
      onChange?.(newValue);
    }
  };

  const sizeConfig = size === 'small'
    ? { width: 46, height: 28, padding: 3, radius: 14, thumb: 22 }
    : { width: 56, height: 32, padding: 4, radius: 16, thumb: 24 };

  const thumbLeft = isChecked
    ? sizeConfig.width - sizeConfig.thumb - sizeConfig.padding
    : sizeConfig.padding;

  const buttonStyle: React.CSSProperties = {
    position: 'relative',
    display: 'inline-flex',
    alignItems: 'center',
    width: `${sizeConfig.width}px`,
    height: `${sizeConfig.height}px`,
    padding: 0,
    border: '1px solid',
    borderRadius: `${sizeConfig.radius}px`,
    background: isChecked
      ? 'linear-gradient(135deg, #ff8a1a 0%, #ff6900 58%, #e25b00 100%)'
      : 'linear-gradient(180deg, #dde4ee 0%, #c7d0dd 100%)',
    borderColor: isChecked ? 'rgba(255, 105, 0, 0.55)' : 'rgba(148, 163, 184, 0.55)',
    cursor: disabled ? 'not-allowed' : 'pointer',
    transition: 'all 0.2s ease',
    opacity: disabled ? 0.5 : 1,
    flexShrink: 0,
    boxShadow: isChecked
      ? '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)',
  };

  const thumbStyle: React.CSSProperties = {
    position: 'absolute',
    top: `${sizeConfig.padding}px`,
    left: `${thumbLeft}px`,
    width: `${sizeConfig.thumb}px`,
    height: `${sizeConfig.thumb}px`,
    borderRadius: '50%',
    backgroundColor: '#fff',
    boxShadow: '0 3px 10px rgba(15, 23, 42, 0.22), 0 1px 2px rgba(15, 23, 42, 0.12)',
    transition: 'left 0.2s ease',
  };

  return (
    <button
      type="button"
      role="switch"
      aria-checked={isChecked}
      className={`prorank-toggle-slider prorank-toggle-slider--${size} ${isChecked ? 'prorank-toggle-slider--checked' : ''} ${disabled ? 'prorank-toggle-slider--disabled' : ''} ${className}`}
      onClick={handleToggle}
      disabled={disabled}
      style={buttonStyle}
    >
      <span className="prorank-toggle-slider__thumb" style={thumbStyle} />
    </button>
  );
};

export default ProrankToggleSlider;
