import { useState } from 'react'
import styled from 'styled-components'

import Input from './input.js'
import { PasswordStrengthMeter } from './password-strength-meter.js'
import { InferComponentProps } from './types.js'

const StyledPasswordStrengthMeter = styled(PasswordStrengthMeter)`
  margin: 0 ${({ theme }) => theme.gu(2)};
  text-align: 'left';
`

type PasswordInputProps = {
  isPasswordShown?: boolean
  passwordStrengthScore: number
  requiredPasswordScore: number
} & Omit<InferComponentProps<typeof Input>, 'childrenBeforeErrors'>
export const PasswordInput = ({
  isPasswordShown,
  passwordStrengthScore,
  requiredPasswordScore,
  className,
  ...props
}: PasswordInputProps) => {
  const [isPasswordShownState, setIsPasswordShownState] = useState(isPasswordShown)
  const handleToggleShowPassword = () => {
    setIsPasswordShownState((isPasswordShownState) => !isPasswordShownState)
  }
  return (
    <Input
      className={className}
      helperText={`${isPasswordShownState ? 'Hide' : 'Show'} password`}
      helperLinkAction={handleToggleShowPassword}
      type={isPasswordShownState ? 'text' : 'password'}
      childrenBeforeErrors={
        passwordStrengthScore >= 0 && (
          <StyledPasswordStrengthMeter
            passwordStrengthScore={passwordStrengthScore}
            requiredPasswordScore={requiredPasswordScore}
          />
        )
      }
      {...props}
    />
  )
}
const StyledPasswordInput = styled(PasswordInput)``
export default StyledPasswordInput
