import React from "react";
import Head from "next/head";
import Image from "next/image";
import Link from "next/link";
import cookie from "cookie";
import { connect } from "react-redux";
import numeral from "numeral";
import pluralize from "pluralize-ru";
import { SpinnerCircular } from "spinners-react";

import { withRouter } from "next/router";
import { reduxWrapper } from "../../store";

import InnerMenu from "../../components/questionnaire/InnerMenu";
import Header from '../components/Header';
import Footer from '../components/Footer';

import {
  sendPhoneChangeNumber,
  sendPhoneChangeNumberSmsCode,
  setUserPhone,
} from "../../actions";
import AccountLayout from "../components/Layout/Account";

class QuestionnairePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: "",
      phone_check_loading: false,
      phone_number_format_error: false,
    };
  }

  componentDidMount() {}

  _handle_onPhoneSubmit = (event) => {
    event.preventDefault();

    const { user, phone, phone_check_loading } = this.state;

    if (!phone_check_loading) {
      this.setState({ phone_check_loading: true }, () => {
        sendPhoneChangeNumber({ email: user.email, phone })
          .then(() => {
            this.setState(
              {
                phone_check_loading: false,
                phone_number_error: false,
                timer: 60,
                phone_form_step: 2,
              },
              () => {
                this.timer_ref = setInterval(() => {
                  const t = this.state.timer - 1;
                  this.setState({ timer: t }, () => {
                    if (t === 0) {
                      clearInterval(this.timer_ref);
                    }
                  });
                }, 1000);
              }
            );
          })
          .catch(() => {
            this.setState({
              phone_number_error: true,
              phone_check_loading: false,
            });
          });
      });
    }
  };

  _handle_onCodeSubmit = (event) => {
    event.preventDefault();

    const { phone, phone_code, code_check_loading } = this.state;

    if (!code_check_loading) {
      this.setState({ code_check_loading: true }, () => {
        sendPhoneChangeNumberSmsCode({ phone, code: phone_code })
          .then(() => {
            const new_user = { ...this.state.user };
            new_user.phone = phone;

            setUserPhone({ dispatch: this.props.dispatch, user: new_user });

            this.setState({
              phone_sms_code_error: false,
              code_check_loading: false,
              phone_form_step: 3,
            });
          })
          .catch(() => {
            this.setState({
              phone_sms_code_error: true,
              code_check_loading: false,
            });
          });
      });
    }
  };

  _handle_onResendCode = (event) => {
    this.setState({ phone_sms_code_error: false }, () => {
      this._handle_onPhoneSubmit(event);
    });
  };

  _handle_onPhoneChange = (value) => {
    const phone_number_format_error =
      value.length > 1 && (value[0] !== "+" || value[1] !== "7") ? true : false;
    this.setState({
      phone: value,
      phone_login_disabled: this._check_fields_disabled([value]),
      phone_number_error: false,
      phone_number_format_error: phone_number_format_error,
    });
  };

  _handle_onPhoneCodeChange = (value) => {
    this.setState({
      phone_code: value,
      phone_code_submit_disabled: this._check_fields_disabled([value]),
      phone_sms_code_error: false,
    });
  };

  _check_fields_disabled = (values) => {
    for (let i in values) {
      if (values[i] === "") {
        return true;
      }
    }

    return false;
  };

	render() 
	{
		const { phone, phone_check_loading, phone_number_format_error } = this.state;

	return (
		<React.Fragment>
			<Head>
				<title>ЛК Эволюция автолизинга - Анкета лизингополучателя</title>
					<meta
						name="description"
						content="ЛК Эволюция автолизинга - Анкета лизингополучателя"
				/>
			</Head>
		<Header {...this.props} />
		<AccountLayout>
			<div className="title_wrapper">
			<div className="left">
				<h1 className="section_title">Анкета лизингополучателя</h1>
			</div>
			</div>
			<div className="aside_container about">
			<article>
				<div className="questionnaire message moderate">
					<svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M22 38.5C31.1127 38.5 38.5 31.1127 38.5 22C38.5 12.8873 31.1127 5.5 22 5.5C12.8873 5.5 5.5 12.8873 5.5 22C5.5 31.1127 12.8873 38.5 22 38.5Z" fill="white"/>
						<path d="M23.0322 14.699L28.301 19.9678L29.0537 22.9785L25.2903 26.7419M14.0478 23.779L19.221 28.9522M18.957 29H14.7527C14.5531 29 14.3616 28.9207 14.2205 28.7795C14.0793 28.6384 14 28.4469 14 28.2473V24.043C14 23.9441 14.0195 23.8463 14.0573 23.7549C14.0951 23.6636 14.1506 23.5806 14.2205 23.5107L25.5107 12.2205C25.6519 12.0793 25.8433 12 26.043 12C26.2426 12 26.434 12.0793 26.5752 12.2205L30.7795 16.4248C30.9207 16.566 31 16.7574 31 16.957C31 17.1567 30.9207 17.3481 30.7795 17.4893L19.4893 28.7795C19.4194 28.8494 19.3364 28.9049 19.2451 28.9427C19.1537 28.9805 19.0559 29 18.957 29Z" stroke="#8E94A7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
					</svg>
					<p>
						<b>Анкета заполнена и ожидает вашего подписания</b>
						Вы заполнили и подписали анкету лизингополучателя посредством
						ЭЦП. Анкета передана в обрабатывающий центр. Если у
						сотрудников возникнут вопросы мы свяжемся с Вами. Спасибо!
					</p>
				</div>
				<div className="questionnaire status_action">
					<button className="button button-blue">
					Загрузить подписанный документ
					</button>
				</div>
				<div className="questionnaire status_action" style={{ width: "100%" }}>
					<div className="docs_list medium-icon">
						<div className="row">
							<p className="doc_name i-pdf extension">
								№1234567 от 21.01.2021
							</p>
							<button className="button button-blue">Отправить</button>
						</div>
					</div>
				</div>
				<div className="questionnaire message success">
					<svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M22 38.5C31.1127 38.5 38.5 31.1127 38.5 22C38.5 12.8873 31.1127 5.5 22 5.5C12.8873 5.5 5.5 12.8873 5.5 22C5.5 31.1127 12.8873 38.5 22 38.5Z" fill="white"/>
						<path d="M29.5625 17.875L19.4791 27.5L14.4375 22.6875" stroke="#5FB158" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round"/>
					</svg>
					<p>
						<b>Анкета заполнена и подписана</b>
						Вы заполнили и подписали анкету лизингополучателя посредством
						загрузки скана анкеты. Анкета передана в обрабатывающий центр.
						Если у сотрудников возникнут вопросы мы свяжемся с Вами.
						Спасибо!
					</p>
				</div>
			</article>
			</div>
		</AccountLayout>
		<Footer />
		</React.Fragment>
	);
	}
}

function mapStateToProps(state, ownProps) {
  return {
    observer: state.auth.observer,
    user: state.user,
  };
}

export const getServerSideProps = reduxWrapper.getServerSideProps(
  (store) =>
    async ({ req, res, query }) => {
      let props = {};

      if (req.headers.cookie !== undefined) {
        const cookies = cookie.parse(
          req.headers?.cookie ? req.headers?.cookie : ""
        );

        if (cookies.jwt === undefined || cookies.jwt === null) {
          res.statusCode = 302;
          res.setHeader("Location", `/login`);
        } else {
          //const tokenValid = await checkToken(cookies.jwt);
          const tokenValid = true;
          if (!tokenValid) {
            res.statusCode = 302;
            res.setHeader("Location", `/login`);
          }
        }
      } else {
        res.statusCode = 302;
        res.setHeader("Location", `/login`);
      }

      return { props: props };
    }
);

export default withRouter(connect(mapStateToProps)(QuestionnairePage));
