import React from 'react';
import { clsx } from 'clsx';

export interface SwitchProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
  checked?: boolean;
  onCheckedChange?: (checked: boolean) => void;
  label?: string;
  description?: string;
}

/**
 * Toggle switch component
 */
export const Switch = React.forwardRef<HTMLInputElement, SwitchProps>(
  (
    {
      checked = false,
      onCheckedChange,
      label,
      description,
      className,
      disabled,
      ...props
    },
    ref
  ) => {
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      onCheckedChange?.(e.target.checked);
    };

    const switchElement = (
      <label
        className={clsx(
          'relative inline-flex items-center cursor-pointer',
          {
            'opacity-50 cursor-not-allowed': disabled,
          },
          className
        )}
      >
        <input
          ref={ref}
          type="checkbox"
          checked={checked}
          onChange={handleChange}
          disabled={disabled}
          className="sr-only peer"
          {...props}
        />
        <div
          className={clsx(
            "relative w-11 h-6 rounded-full transition-colors duration-200",
            "peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary peer-focus:ring-offset-2",
            {
              "bg-primary": checked && !disabled,
              "bg-muted": !checked || disabled,
            }
          )}
        >
          <div
            className={clsx(
              "absolute top-0.5 left-0.5 w-5 h-5 rounded-full transition-transform duration-200",
              "bg-white shadow-sm",
              {
                "translate-x-5": checked,
                "translate-x-0": !checked,
              }
            )}
          />
        </div>
      </label>
    );

    if (label || description) {
      return (
        <div className="flex items-start gap-3">
          {switchElement}
          <div className="flex flex-col">
            {label && (
              <span
                className={clsx('text-sm font-medium', {
                  'text-muted-foreground': disabled,
                })}
              >
                {label}
              </span>
            )}
            {description && (
              <span
                className={clsx('text-xs text-muted-foreground mt-0.5', {
                  'opacity-70': disabled,
                })}
              >
                {description}
              </span>
            )}
          </div>
        </div>
      );
    }

    return switchElement;
  }
);
Switch.displayName = 'Switch';

