import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { selectors } from '../../store'
import { useAuth } from '../../auth'
import { useApi, useApiCall, SubscriptionCheckout } from '../../api'
import UserHeader from '../UserHeader'
import Title from '../Title'
import Loader from '../Loader'
import MainButton from '../MainButton'
import applePaySafeCheckout from './Apple-Pay.png'
import gPaySafeCheckout from './Google-Pay.png'
import secure from './Secure.png'
import ApplePay from './Apple-Pay.svg'
import GooglePay from './G-Pay.svg'
import card from './card.svg'
import routes from '../../routes'
import './styles.css'

const isAndroid = () => /Android/i.test(navigator.userAgent)
const isApple = () => /Macintosh|iPhone|iPad|iPod/i.test(navigator.userAgent)

function PaymentPage(): JSX.Element {
  const api = useApi()
  const { token } = useAuth()
  const { t, i18n } = useTranslation()
  const locale = i18n.language
  const navigate = useNavigate()
  const email = useSelector(selectors.selectEmail)
  const handleClick = () => navigate(routes.client.wallpaper())
  const loadData = useCallback(() => {
    return api.getSubscriptionItems({ locale, token })
      .then(({ item_prices }) => item_prices.find(({ id }) => id === 'aura-membership-2-week-USD'))
      .then((item) => api.getSubscriptionCheckout({ locale, token, itemPriceId: item?.id || '' }))
  }, [api, locale, token])
  const { data, isPending } = useApiCall<SubscriptionCheckout.Response>(loadData)
  console.log(data, isPending)
  return (
    <>
      <UserHeader email={email} />
      <section className='page'>
        <div className='page-header'>
          {isAndroid() && <img src={gPaySafeCheckout} alt='Guaranteed safe checkout' />}
          {isApple() && <img src={applePaySafeCheckout} alt='Guaranteed safe checkout' />}
          <img src={secure} alt='100% Secure' />
        </div>
        <Title variant='h1' className='mb-45'>{t('choose_payment')}</Title>
        {isPending ? <Loader /> : (
          <>
            <MainButton onClick={handleClick}>
              {isAndroid() && <img className='payment-btn' src={GooglePay} alt='Google Pay' />}
              {isApple() && <img className='payment-btn' src={ApplePay} alt='Apple Pay' />}
            </MainButton>
            <div className='payment-divider'>{t('or').toUpperCase()}</div>
            <MainButton color='blue' onClick={handleClick}>
              <img className='payment-card' src={card} alt='Credit / Debit Card' />
              {t('card')}
            </MainButton>
            <p className='payment-warining'>You will be charged only <strong>$1 for your 7-day trial</strong>. We'll email your a reminder before your trial period ends.</p>
          </>
        )}
      </section>
    </>
  )
}

export default PaymentPage
