import { useRouteMatch } from 'react-router-dom'
import {
  CardNumberElement,
  CardExpiryElement,
  CardCvcElement,
} from '@stripe/react-stripe-js'

import { isMobileDevice } from 'config/userAgent'
import { PAGES } from 'config/pages'

import { T9n } from 'features/T9n'
import { useCardsStore } from 'features/CardsStore'
import { ArrowLoader } from 'features/ArrowLoader'

import { ElementContainer } from '../ElementContainer'

import type { Props } from './hooks'
import { useFormSubmit, ElementTypes } from './hooks'

import {
  Form,
  Column,
  CountryWrapper,
  CustomCombobox,
  ButtonsBlock,
  Input,
  Errors,
  SectionTitle,
} from '../../styled'

const autoFillStyles = {
  ':-webkit-autofill': {
    color: '#fff',
  },
}

const baseStyles = isMobileDevice
  ? {
    color: '#fff',
    fontSize: '12px',
    fontWeight: 'bold',
    lineHeight: '12px',
    ...autoFillStyles,
  }
  : {
    color: '#fff',
    fontFamily: 'Montserrat, Tahoma, sans-serif',
    fontSize: '20px',
    fontWeight: 'bold',
    lineHeight: '48px',
    ...autoFillStyles,
  }

const options = { placeholder: '', style: { base: baseStyles } }

export const AddCardFormInner = (props: Props) => {
  const {
    children,
    inputsBackground,
  } = props
  const { error: cardError } = useCardsStore()

  const isUserAccountPage = useRouteMatch(PAGES.useraccount)?.path === PAGES.useraccount

  const calcWidth = () => {
    switch (true) {
      case isUsaCountry:
        return '100%'
      case isMobileDevice:
        return '48%'
      default:
        return '275px'
    }
  }

  const {
    address,
    city,
    countries,
    errorMessage,
    handleSubmit,
    isLabelVisible,
    loader,
    name,
    onAddressChange,
    onCityChange,
    onCountryChange,
    onInputsBlur,
    onInputsChange,
    onInputsFocus,
    onNameChange,
    onStateChange,
    onStateSelect,
    selectedCountry,
    selectedState,
    usaStates,
    usaStateValue,
  } = useFormSubmit(props)

  const isUsaCountry = selectedCountry?.id === 194

  return (
    <Form onSubmit={handleSubmit}>
      <SectionTitle>
        <T9n t='adding_card' />
      </SectionTitle>
      <Column>
        <ElementContainer
          label={isLabelVisible(ElementTypes.CardNumber) ? 'form_card_number' : ''}
          backgroundColor={inputsBackground}
        >
          <CardNumberElement
            options={options}
            onChange={onInputsChange}
            onFocus={onInputsFocus(ElementTypes.CardNumber)}
            onBlur={onInputsBlur(ElementTypes.CardNumber)}
          />
        </ElementContainer>

        <ElementContainer
          label={isLabelVisible(ElementTypes.CardHolder) ? 'card_holder_name' : ''}
          backgroundColor={inputsBackground}
        >
          {/* не удаляем, без Form автозаполнение не работает */}
          <Form>
            <Input
              type='text'
              name='ccname'
              autoComplete='cc-name'
              value={name}
              onChange={onNameChange}
              onFocus={onInputsFocus(ElementTypes.CardHolder)}
              onBlur={onInputsBlur(ElementTypes.CardHolder)}
            />
          </Form>
        </ElementContainer>

        <ElementContainer
          label={isLabelVisible(ElementTypes.CardExpiry) ? 'form_card_expiration' : ''}
          width='275px'
          className='test_class'
          backgroundColor={inputsBackground}
        >
          <CardExpiryElement
            options={options}
            onChange={onInputsChange}
            onFocus={onInputsFocus(ElementTypes.CardExpiry)}
            onBlur={onInputsBlur(ElementTypes.CardExpiry)}
          />
        </ElementContainer>

        <ElementContainer
          label={isLabelVisible(ElementTypes.CardCvc) ? 'form_card_code' : ''}
          width='275px'
          backgroundColor={inputsBackground}
        >
          <CardCvcElement
            options={options}
            onChange={onInputsChange}
            onFocus={onInputsFocus(ElementTypes.CardCvc)}
            onBlur={onInputsBlur(ElementTypes.CardCvc)}
          />
        </ElementContainer>
      </Column>
      <SectionTitle>
        <T9n t='billing_address' />
      </SectionTitle>
      <Column>
        <CountryWrapper>
          <CustomCombobox
            value={selectedCountry?.name || ''}
            labelLexic={selectedCountry?.name ? '' : 'country'}
            onSelect={onCountryChange}
            onBlur={onInputsBlur(ElementTypes.CardCountry)}
            options={countries}
            withError={false}
            selected={Boolean(selectedCountry?.name)}
            noSearch
          />
        </CountryWrapper>
        {isUsaCountry && (
          <CountryWrapper>
            <CustomCombobox
              value={usaStateValue || selectedState?.name || ''}
              labelLexic={selectedState?.name ? '' : 'state'}
              onSelect={onStateSelect}
              onBlur={onInputsBlur(ElementTypes.CardState)}
              options={usaStates.filter(
                (state) => (state.name_eng.toLowerCase().includes(usaStateValue.toLowerCase())),
              )}
              withError={false}
              selected={Boolean(selectedState?.name)}
              onChange={onStateChange}
            />
          </CountryWrapper>
        )}

        <ElementContainer
          label={isLabelVisible(ElementTypes.CardCity) ? 'city' : ''}
          width={calcWidth()}
          backgroundColor={inputsBackground}
          className={isUsaCountry ? 'CardForm__cityInput' : ''}
        >
          <Input
            type='text'
            autoComplete='address-level2'
            value={city}
            onChange={onCityChange}
            onFocus={onInputsFocus(ElementTypes.CardCity)}
            onBlur={onInputsBlur(ElementTypes.CardCity)}
          />
        </ElementContainer>
        <ElementContainer
          label={isLabelVisible(ElementTypes.CardAddress) ? 'address' : ''}
          width='100%'
          backgroundColor={inputsBackground}
          className={isUsaCountry ? 'CardForm__cityInput AddCardForm_Address' : 'AddCardForm_Address'}
        >
          <Input
            type='text'
            autoComplete='street-address'
            value={address}
            onChange={onAddressChange}
            onFocus={onInputsFocus(ElementTypes.CardAddress)}
            onBlur={onInputsBlur(ElementTypes.CardAddress)}
            className='ChangeCard__Form__Address'
          />
        </ElementContainer>
      </Column>
      <ButtonsBlock isUserAccountPage={isUserAccountPage}>
        {(errorMessage || cardError) && (
          <Errors>
            {errorMessage}
            <T9n t={cardError} />
          </Errors>
        ) }
        {loader ? <ArrowLoader disabled width='204px' /> : children}
      </ButtonsBlock>
    </Form>
  )
}
