import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';
import axios from 'axios';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import GenericForm from 'components/forms/GenericForm';
import GenericFields from 'components/formHelpers/GenericFields/GenericFields';
import { Form } from 'react-final-form';
import ModuleButton from 'components/items/ModuleButton';
import settings from 'store/settings';
import { withRouter } from 'react-router-dom';
import qs from 'query-string';
import moment from 'moment';
import { axiosCall } from 'store/utils/api';
import { BiRefresh } from 'react-icons/bi';
import app from 'store/app';
import styleIdentifiers from './instagram.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type InstagramProps = StateProps & DispatchProps & OwnProps;

const FormAccessTokenData = props => {
  const { handleSubmit, submitting, valid } = props;
  return (
    <form className={styles('ParticipantForm')} onSubmit={handleSubmit}>
      <GenericFields
        finalForm
        fields={[{ label: 'Access Token', name: 'access_token', type: 'string', required: true }]}
      />
      <div className={styles('button')}>
        <ModuleButton disabled={submitting || !valid} label="Validate" type="submit" />
      </div>
    </form>
  );
};

const FormUriData = props => {
  const { handleSubmit, submitting, valid } = props;
  return (
    <form className={styles('ParticipantForm')} onSubmit={handleSubmit}>
      <GenericFields
        finalForm
        fields={[
          { label: 'App ID', name: 'app_id', type: 'string', required: true },
          { label: 'App Secret', name: 'app_secret', type: 'password', required: true },
          { label: 'Redirect Uri', name: 'redirect_uri', type: 'string', required: true },
        ]}
      />
      <div className={styles('button')}>
        <ModuleButton disabled={submitting || !valid} label="Authenticate" type="submit" />
      </div>
    </form>
  );
};

const Instagram = (props: InstagramProps) => {
  const { location } = props;

  const [code, setCode] = useState(null);
  const [authenticate, setAuthenticate] = useState(false);
  const [accessToken, setAccessToken] = useState(null);

  // mapStateToProps
  const projectSettings = useSelector((state: StoreState) => state.settings.project?.data);
  const instaData = useSelector((state: StoreState) => state.settings.instagram?.data);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  useEffect(() => {
    if (location?.search) {
      const res = qs.parse(location.search);
      if (res.code) {
        setCode(res.code);
        setAuthenticate(true);
      }
    }
  }, [location]);

  useEffect(() => {
    dispatch(settings.actions.integrations.instagram.post.request.action());
  }, []);

  function findVariable(key, asObject) {
    const item = projectSettings?.find(e => e.key === key);
    if (item && !asObject) return item.value;
    if (item && asObject) return item;
    return null;
  }

  function saveVariable(key, val) {
    const prev = findVariable(key, true);

    if (!prev) {
      dispatch(
        settings.actions.addProjectSettings.request.action({
          data: {
            input: { key, value: val },
          },
        }),
      );
    } else {
      dispatch(
        settings.actions.editProjectSettings.request.action({
          data: {
            input: { value: val },
            id: prev._id,
          },
        }),
      );
    }
  }

  function authenticateUser(val) {
    saveVariable('INSTAGRAM_APP_ID', val.app_id);
    saveVariable('INSTAGRAM_APP_SECRET', val.app_secret);
    saveVariable('INSTAGRAM_REDIRECT_URI', val.redirect_uri);
    window.open(
      `https://api.instagram.com/oauth/authorize?client_id=${val.app_id}&redirect_uri=${val.redirect_uri}&scope=user_profile,user_media&response_type=code`,
    );
  }

  function crawlPost() {
    dispatch(settings.actions.integrations.instagram.crawl.request.action());
  }

  function genToken() {
    dispatch(
      settings.actions.integrations.instagram.generate.request.action({
        code,
        callback: res => {
          if (res?.message) dispatch(app.actions.dialog.success.action({ data: res.message }));
        },
      }),
    );
  }

  return (
    <div className={styles('instagram')}>
      <div className={styles('content')}>
        <div className={styles('section-wrapper')}>
          <h3 className={styles('section-title')}>Step 1 - Authenticate</h3>
          <div className={styles('section-text')}>
            <div>
              <div>Follow step until step 3</div>
              <a
                href="https://developers.facebook.com/docs/instagram-basic-display-api/getting-started"
                target="_blank"
                rel="noopener noreferrer"
              >
                https://developers.facebook.com/docs/instagram-basic-display-api/getting-started
              </a>
            </div>
          </div>
          <div>
            <h4>Authenticate User</h4>
            {!authenticate ? (
              <Form
                component={FormUriData}
                initialValues={{
                  // eslint-disable-next-line
                  app_id: findVariable('INSTAGRAM_APP_ID'),
                  // eslint-disable-next-line
                  redirect_uri: findVariable('INSTAGRAM_REDIRECT_URI'),
                  // eslint-disable-next-line
                  app_secret: findVariable('INSTAGRAM_APP_SECRET'),
                }}
                onSubmit={authenticateUser}
              />
            ) : (
              <div>
                Authenticate Success
                <ModuleButton type="button" onClick={() => setAuthenticate(false)}>
                  ReAuthenticate
                </ModuleButton>
              </div>
            )}
          </div>
        </div>
        {code && (
          <div className={styles('section-wrapper')}>
            <h3 className={styles('section-title')}>Step 2 - Token Generation</h3>
            <ModuleButton
              action={genToken}
              label="Generate Token"
              noMargin
              relative
              className={styles('button')}
            />
          </div>
        )}
      </div>
      <div className={styles('posts')}>
        <div className={styles('title')}>
          Posts Crawled
          <div className={styles('info')}>
            <div className={styles('text')}>
              {`Crawled date: ${moment(instaData?.crawlDate).format('MMM DD/YYYY - HH:mm')}`}
            </div>
            <ModuleButton action={crawlPost} noMargin relative className={styles('button')}>
              <BiRefresh />
            </ModuleButton>
          </div>
        </div>
        <div className={styles('post-container')}>
          {instaData?.posts?.map((el, key) => (
            <div className={styles('post-item')} key={key}>
              <a href={el.permalink} target="_blank" rel="noopener noreferrer">
                {el.permalink}
              </a>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default withRouter(Instagram);
