import { forwardRef, useCallback, useId, useState } from 'react';
import { Input } from './Input';
import type { InputProps } from './Input';

export type PasswordInputProps = Omit<InputProps, 'type' | 'endAdornment'>;

function IconEye() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden focusable="false">
      <path
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
      />
      <circle fill="none" stroke="currentColor" strokeWidth="2" cx="12" cy="12" r="3" />
    </svg>
  );
}

function IconEyeSlash() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden focusable="false">
      <path
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"
      />
      <path fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" d="M1 1l22 22" />
    </svg>
  );
}

export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(function PasswordInput(
  { autoComplete = 'current-password', disabled, readOnly, ...rest },
  ref
) {
  const toggleId = useId().replace(/:/g, '');
  const [visible, setVisible] = useState(false);

  const toggle = useCallback(() => {
    if (disabled || readOnly) return;
    setVisible((v) => !v);
  }, [disabled, readOnly]);

  const showPassword = visible;
  const labelShow = 'Show password';
  const labelHide = 'Hide password';

  return (
    <Input
      ref={ref}
      {...rest}
      type={showPassword ? 'text' : 'password'}
      autoComplete={autoComplete}
      disabled={disabled}
      readOnly={readOnly}
      endAdornment={
        <button
          type="button"
          id={`${toggleId}-pw-toggle`}
          className="ccl-input-group__toggle"
          disabled={disabled || readOnly}
          aria-pressed={showPassword}
          aria-label={showPassword ? labelHide : labelShow}
          onClick={toggle}
        >
          {showPassword ? <IconEyeSlash /> : <IconEye />}
        </button>
      }
    />
  );
});
