import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Eye, EyeOff } from 'lucide-react';
import { cn } from '../../lib/utils';

const inputVariants = cva('shInput', {
  variants: {
    size: {
      xs: 'shControlXs',
      sm: 'shControlSm',
      md: 'shControlMd',
      lg: 'shControlLg',
      xl: 'shControlXl',
    },
  },
  defaultVariants: {
    size: 'md',
  },
});

export interface InputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'>,
    VariantProps<typeof inputVariants> {}

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, size, ...props }, ref) => <input ref={ref} className={cn(inputVariants({ size, className }))} {...props} />,
);

Input.displayName = 'Input';

export interface PasswordInputProps extends Omit<InputProps, 'type'> {
  hidePasswordLabel?: string;
  showPasswordLabel?: string;
}

export const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
  (
    {
      className,
      disabled,
      hidePasswordLabel = '隐藏密码',
      showPasswordLabel = '显示密码',
      size,
      ...props
    },
    ref,
  ) => {
    const [passwordVisible, setPasswordVisible] = React.useState(false);
    const toggleLabel = passwordVisible ? hidePasswordLabel : showPasswordLabel;
    const VisibilityIcon = passwordVisible ? EyeOff : Eye;

    return (
      <div className="shPasswordInputRoot">
        <Input
          ref={ref}
          className={cn('shPasswordInput', className)}
          disabled={disabled}
          size={size}
          type={passwordVisible ? 'text' : 'password'}
          {...props}
        />
        <button
          type="button"
          className="shPasswordInputToggle"
          aria-label={toggleLabel}
          aria-pressed={passwordVisible}
          disabled={disabled}
          title={toggleLabel}
          onClick={() => setPasswordVisible((visible) => !visible)}
        >
          <VisibilityIcon aria-hidden="true" size={16} />
        </button>
      </div>
    );
  },
);

PasswordInput.displayName = 'PasswordInput';
