import React, { useState } from 'react';
import Axios from 'axios';
import Flexbox from 'flexbox-react';
import Countdown from 'react-countdown-now';
import Checkbox from '../../Checkbox/Checkbox';
import * as S from './styles';
import Input from '../../Input';
import COUNTRIES_MAP from './lib';

const PredictFooter = ({
  push,
  userId,
  country,
  isValid,
  userCountry,
  challengeId,
  matches = [],
  roundDateDue,
  onRoundFinished,
  setFieldValue,
  phoneNumber,
}) => {
  const date = new Date();
  const daysLeft = Math.floor((roundDateDue - date) / 3600000 / 24);
  const hoursLeft = Math.floor((roundDateDue - date) / 3600000) - daysLeft * 24;

  const getFlag = () => {
    const slicedV = (phoneNumber && phoneNumber.replace(/[()]/g, '')) || '';
    const c = COUNTRIES_MAP.find(({ dial_code }) => slicedV.startsWith(dial_code));
    const { flag: prefillFlag, dial_code: prefillDialCode } = COUNTRIES_MAP.find(({ code }) => code === userCountry) || {};
    if (phoneNumber === '' && COUNTRIES_MAP.find(({ code }) => code === userCountry)) {
      setFieldValue('phoneNumber', prefillDialCode);
    }
    return c && phoneNumber !== '' ? c.flag : prefillFlag || ('🌐');
  };
  const predictionsLeft = matches.filter(({ value }) => !value).length;
  const btnOverlayWidth = (100 / matches.length) * (matches.length - predictionsLeft);
  const [check, setCheck] = useState(false);
  const [hasAccount, setHasAccount] = useState(false);
  return (
    <Flexbox
      width="80%"
      margin="auto"
      display="flex"
      alignItems="center"
      justifyContent="space-between"
      flexDirection="column"
      style={{
        bottom: 0,
        color: '#fff',
        padding: '15px',
        position: 'fixed',
        background: '#122336',
        width: 'calc(100vw - 30px)',
        boxShadow: '0px -8px 24px rgba(0, 15, 31, 0.32), inset 0px 1px 0px #19324D',
        '-webkit-backface-visibility': 'hidden',
      }}
    >

      <Flexbox
        flexDirection="row"
        width="100%"
        justifyContent="space-between"
        alignItems="center"
        alignContent="center"
      >
        {predictionsLeft || hasAccount ? (

          <>
            <Flexbox flexDirection="column" alignContent="center" width="140px">
              {hasAccount ? (
                <span>
                  You already have an account
                </span>
              ) : (
                <>
                  <b>
                    {daysLeft >= 1 ? `${daysLeft}d ${hoursLeft}h` : (
                      <Countdown
                        daysInHours
                        key={roundDateDue}
                        date={roundDateDue}
                        style={{ padding: '2%' }}
                        onComplete={() => onRoundFinished(userId)}
                      />
                    )}
                  </b>
                  <span>
                    {' '}
                    Time
                    {' '}
                    left
                  </span>
                </>
              )}
            </Flexbox>
          </>
        ) : (
          <Flexbox flexDirection="column">
            <Flexbox
              width="100%"
              alignItems="center"
              paddingBottom="10px"
            >
              <Checkbox
                name="agree"
                checked={check}
                label="I am over 18 years old"
                onChange={() => setCheck(!check)}
              />
            </Flexbox>
            <Input
              inlineCss={`
                width: 100%;
                & > input {
                  font-size: 16px;
                }
              `}
              autocomplete="on"
              autoFocus
              type="tel"
              name="phoneNumber"
              prefix={getFlag()}
              mask={{ mask: '+00(000)0000000' }}
            />
          </Flexbox>
        )}

        <S.NextBtn
          style={{
            height: '46px',
            alignSelf: 'flex-end',
          }}
          isValid={isValid && phoneNumber.length >= 14 && check}
          onClick={async () => {
            if (isValid && check) {
              await Axios.post(`${process.env.API_STAGING}/`, {
                userId,
                country,
                challengeId,
                notifyFriends: '',
                provider: process.env.CHALLENGE_PROVIDER,
                matches: matches.map((({ id, value }) => ({ matchId: id, prediction: value }))),
              });
              Axios.get(`${process.env.API_STAGING}/verify`, {
                responseType: 'json',
                params: {
                  userId,
                  country,
                  challengeId,
                  provider: process.env.CHALLENGE_PROVIDER,
                  number: phoneNumber.replace(/[^\d^+]/g, ''),
                },
              }).then(() => {
                push({
                  pathname: '/verify',
                  query: {
                    userId,
                    country,
                    phoneNumber,
                    provider: process.env.CHALLENGE_PROVIDER,
                  },
                });
              }).catch((e) => setHasAccount(true));
            }
          }}
        >
          <span>
            {!hasAccount ? 'Next' : <a href={`${process.env.APP_DEEPLINK}?phoneNumber=${phoneNumber}`}>Sign In</a>}
          </span>
          <S.NextBtnOverlay width={btnOverlayWidth} />
        </S.NextBtn>
      </Flexbox>
    </Flexbox>
  );
};

PredictFooter.propTypes = {

};

export default PredictFooter;
