/* eslint-disable @typescript-eslint/no-explicit-any */
import { Box, PasswordInput, Popover, Progress, rem } from '@mantine/core'
import { IconCheck, IconX } from '@tabler/icons-react'
import { useState } from 'react'

const PasswordRequirementWithForm = ({
  requirements,
  form,
  label,
  placeholder,
  required,
  name,
  mb,
}: {
  requirements: any[]
  form: any
  label: string
  placeholder: string
  required: boolean
  name: string
  mb?: string
}) => {
  const [popoverOpened, setPopoverOpened] = useState(false)
  const strength = getStrength(form.values[name])
  const color = strength === 100 ? 'teal' : 'red'
  const checks = requirements.map((requirement: any, index: number) => (
    <PasswordRequirement
      key={index}
      label={requirement.label}
      meets={requirement.re.test(form.values[name])}
    />
  ))
  function getStrength(password: string) {
    let multiplier = 0

    requirements.forEach((requirement: any) => {
      if (!requirement.re.test(password)) {
        multiplier += 1
      }
    })

    return 100 - (100 / requirements.length) * multiplier
  }

  function PasswordRequirement({
    meets,
    label,
  }: {
    meets: boolean
    label: string
  }) {
    return (
      <Box
        c={meets ? 'teal' : 'red'}
        style={{
          display: 'flex',
          alignItems: 'center',
        }}
        mt={7}
        fz={'0.8rem'}
        size="sm"
      >
        {meets ? (
          <IconCheck
            style={{
              width: rem(14),
              height: rem(14),
            }}
          />
        ) : (
          <IconX style={{ width: rem(14), height: rem(14) }} />
        )}{' '}
        <Box ml={10}>{label}</Box>
      </Box>
    )
  }

  return (
    <Popover
      opened={popoverOpened}
      withArrow
      position="right-end"
      width="target"
      transitionProps={{ transition: 'pop' }}
    >
      <Popover.Target>
        <div
          onFocusCapture={() => setPopoverOpened(true)}
          onBlurCapture={() => setPopoverOpened(false)}
        >
          <PasswordInput
            mb={mb}
            required={required}
            label={label}
            maxLength={32}
            name={name}
            placeholder={placeholder}
            error={form.errors[name]}
            value={form.values[name]}
            onChange={(event) =>
              form.setFieldValue(name, event.currentTarget.value)
            }
          />
        </div>
      </Popover.Target>
      <Popover.Dropdown>
        <Progress color={color} value={strength} size={4} mb="xs" />
        {checks}
      </Popover.Dropdown>
    </Popover>
  )
}

export default PasswordRequirementWithForm
