import type { ChangeEvent, FocusEvent } from 'react'
import { useRouteMatch } from 'react-router-dom'

import { T9n } from 'features/T9n'
import { useLexicsStore } from 'features/LexicsStore'
import { PAGES } from 'config'

import {
  WrapperProps,
  InputWrapper,
  InputStyled,
  Label,
  LabelTitle,
  Error,
  Icon,
  Column,
} from './styled'

type Props = {
  autoComplete?: string,
  className?: string,
  defaultValue?: string,
  disabled?: boolean,
  editIcon?: boolean,
  inputWidth?: number,
  label?: string,
  labelLexic?: string,
  labelWidth?: number,
  maxLength?: number,
  onBlur?: (event: FocusEvent<HTMLInputElement>) => void,
  onChange?: (event: ChangeEvent<HTMLInputElement>) => void,
  onFocus?: (event: FocusEvent<HTMLInputElement>) => void,
  pattern?: string,
  required?: boolean,
  title?: string,
  type?: string,
  value?: string,
  withError?: boolean,
} & WrapperProps

export const Input = ({
  autoComplete = '',
  className,
  defaultValue,
  disabled,
  editIcon = false,
  error,
  inputWidth,
  label,
  labelLexic,
  labelWidth,
  maxLength,
  onBlur,
  onChange,
  onFocus,
  pattern,
  required,
  title,
  type,
  value,
  withError = true,
  wrapperWidth,
}: Props) => {
  const { translate } = useLexicsStore()
  const isUserAccountPage = useRouteMatch(PAGES.useraccount)?.isExact || false

  return (
    <Column isUserAccountPage={isUserAccountPage} className={className}>
      <InputWrapper
        wrapperWidth={wrapperWidth}
        hasRightIcon={editIcon}
        error={error}
      >
        <Label>
          <LabelTitle labelWidth={labelWidth} isUserAccountPage={isUserAccountPage}>
            {labelLexic ? <T9n t={labelLexic} /> : label}
          </LabelTitle>
          <InputStyled
            autoComplete={autoComplete}
            type={type}
            required={required}
            value={value}
            defaultValue={defaultValue}
            disabled={disabled}
            onChange={onChange}
            onBlur={onBlur}
            onFocus={onFocus}
            maxLength={maxLength}
            inputWidth={inputWidth}
            pattern={pattern}
            title={title}
            placeholder={translate(labelLexic || '')}
            isUserAccountPage={isUserAccountPage}
          />
          {editIcon && <Icon image='edit-icon' />}
        </Label>
      </InputWrapper>
      {withError && <Error t={error || ''} />}
    </Column>
  )
}
