/* eslint-disable react/no-array-index-key */
import React, { useEffect, useState } from 'react';
import Axios from 'axios';
import * as Yup from 'yup';
import cookie from 'js-cookie';
import { Formik } from 'formik';
import { generate } from 'shortid';
import Flexbox from 'flexbox-react';
import { string } from 'prop-types';
import nextCookie from 'next-cookies';
import { useRouter } from 'next/router';

import * as S from './styles';
import MatchRow from '../../components/Predict/MatchRow';
import PredictFooter from '../../components/Predict/PredictFooter';

const VALIDATION_SCHEMA = Yup.object().shape({
  matches: Yup.array().of(
    Yup.object().shape({
      id: Yup.string().required(),
      value: Yup.string().required(),
    }),
  ).required(),
});

Axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';

const PredictContainer = ({ country, userId }) => {
  const { push, query: { mid = [], p = [] } } = useRouter();
  const bannerPredictions = Array.isArray(mid)
    ? mid.map((id, idx) => ({ id: Number(id), value: p[idx] }))
    : [{ id: Number(mid), value: p }];
  const [matches, setMatches] = useState([]);
  const [userCountry, setUserCountry] = useState(null);
  const [challengeId, setChallengeId] = useState(null);
  const [roundDateDue, setRoundDateDue] = useState(null);
  const getMatches = () => {
    Axios.get(`${process.env.API_STAGING}/`, {
      crossDomain: true,
      params: {
        country,
        userId: userId || cookie.get('userId'),
        provider: process.env.CHALLENGE_PROVIDER, // temporary should be changed to Suberbet?
      },
    }).then(((res) => {
      const { data: { currentChallenge, nextChallenge } } = res;
      if (currentChallenge.predictionsEnabled) {
        setMatches(currentChallenge.matches);
        setChallengeId(currentChallenge.challengeId);
        setRoundDateDue(new Date(`${currentChallenge.predictionsDisableAt}.000Z`));
      } else {
        setMatches(nextChallenge.matches);
        setChallengeId(nextChallenge.challengeId);
        setRoundDateDue(new Date(`${nextChallenge.predictionsDisableAt}.000Z`));
      }
    }))
      .catch(({ response }) => {
        if (response.status === 403) {
          cookie.remove('userId');
          cookie.remove('userCountry');
          push('/');
        }
      });
  };

  useEffect(() => {
    const getCountryByIp = async () => {
      if (!cookie.get('userCountry')) {
        const { data } = await Axios.get(`https://api.ipstack.com/check?access_key=${process.env.IP_STACK_ACCESS_KEY}`);
        cookie.set('userCountry', data.country_code, { expires: 14 });
        setUserCountry(data.country_code);
      } else {
        setUserCountry(cookie.get('userCountry'));
      }
    };
    if (!cookie.get('userId')) {
      cookie.set('userId', userId, { expires: 14 });
    }
    getMatches();
    getCountryByIp();
  }, []);
  return (
    <S.Wrapper key={roundDateDue}>
      <S.HeaderImage width="100%" src="/assets/predict/predict-page-bg.png" alt="Main bg" />
      <Flexbox flexDirection="column" display="flex" alignItems="center">
        <Formik
          validateOnBlur
          validateOnMount
          validateOnChange
          enableReinitialize
          validationSchema={VALIDATION_SCHEMA}
          style={{ 'background-color': '#f5f5f5', height: '40px' }}
          initialValues={{
            phoneNumber: '',
            matches: matches.map(({ matchId }) => ({
              id: matchId,
              value: (bannerPredictions.find(({ id }) => id === matchId) || {}).value || null,
            })),
          }}
        >
          {({
            isValid, values, setFieldValue,
          }) => (matches.length ? (
            <>
              {matches.map((match, idx) => (
                <MatchRow
                  key={idx}
                  rowIdx={idx}
                  match={match}
                  preselected={(bannerPredictions.find(({ id }) => id === match.matchId) || {}).value}
                  setFieldValue={(value) => setFieldValue(`matches[${idx}]`, { id: match.matchId, value })}
                />
              ))}
              <PredictFooter
                push={push}
                userId={userId}
                country={country}
                userCountry={userCountry}
                isValid={isValid}
                setFieldValue={setFieldValue}
                matches={values.matches}
                challengeId={challengeId}
                roundDateDue={roundDateDue}
                onRoundFinished={getMatches}
                phoneNumber={values.phoneNumber}
                bannerPredictions={bannerPredictions}
              />
            </>
          ) : ('...'))}
        </Formik>
      </Flexbox>
    </S.Wrapper>
  );
};

PredictContainer.getInitialProps = async (ctx) => {
  const { userId } = nextCookie(ctx);
  const generatedUserId = generate();
  const country = process.env.CHALLENGE_COUNTRY;
  if (!userId) {
    try {
      await Axios.post(`${process.env.API_STAGING}/signup/`, {
        country,
        pushToken: '',
        userId: generatedUserId,
        provider: process.env.CHALLENGE_PROVIDER, // temporary should be changed to Suberbet?
      });
    } catch (error) {
      console.log('TCL: PredictContainer.getInitialProps -> error', error);
    }
  }
  return { country, userId: userId || generatedUserId };
};

PredictContainer.propTypes = {
  country: string.isRequired,
  userId: string.isRequired,
};

export default PredictContainer;
