import React from "react";

import PropTypes from "prop-types";

import axios from "axios";
import qs from "qs"; //post to php w/o file_get_contents('php://input');

import { Loader, Button, Icon, Message } from "semantic-ui-react";

export default class ContactCheck extends React.Component {
  //checks server for contact (login) and specific configuration

  static propTypes = {
    appState: PropTypes.object.isRequired,
    appStateUpdate: PropTypes.func.isRequired,
    callURL: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.devMode = props.appState.devMode;

    this.serverCalled = false;
    this.axiosConfig = {
      withCredentials: true,
      credentials: "include",
      timeout: 10000,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      },
    };

    this.state = {
      info: "Checking login and contact info ...",
      loading: true,
      error: false,
      timedOut: false,
    };
  }

  getErrorInfo(error) {
    const timedOut =
      error?.code === "ECONNABORTED" ||
      String(error?.message || "")
        .toLowerCase()
        .includes("timeout");

    return {
      timedOut,
      message: timedOut
        ? this.txt("Connection timed out. Please retry.")
        : error?.response?.data?.info ||
          error?.message ||
          this.txt("Could not connect to server. Please retry."),
    };
  }

  continueWithoutCheck = () => {
    this.props.appStateUpdate(
      { contactCheck: true, session: { login: 0, error: 1 } },
      { screen: true }
    );
  };

  txt = (text) => {
    const { props } = this;
    if (!props.appState.config?.text) return text;
    if (text in props.appState.config.text) return props.appState.config.text[text];
    return text;
  };

  serverCall() {
    const { props } = this;
    const self = this;

    const urlParams = new URLSearchParams(window ? window.location.search : {});
    var content_id = urlParams.get("content"); //ticket for content
    var creator_id = urlParams.get("creator"); //ticket for a creator
    var site_id = urlParams.get("site"); //ticket from a site

    var ticket_id = urlParams.get("ticket"); //ticket id number
    var form = urlParams.get("form"); //form name
    var department = urlParams.get("department"); //department name
    var lead = urlParams.get("lead"); //opaque Lead Form CRM token

    //JS embed parameters
    const vwParams = window.VideoWhisperSupport;
    if (vwParams) {
      if (vwParams.creator) if (!creator_id) creator_id = vwParams.creator;
      if (vwParams.content) if (!content_id) content_id = vwParams.content;
      if (vwParams.site) if (!site_id) site_id = vwParams.site;
      if (vwParams.form) if (!form) form = vwParams.form;
      if (vwParams.department) if (!department) department = vwParams.department;
      if (vwParams.ticket) if (!ticket_id) ticket_id = vwParams.ticket;
    }

    //collect unknown url params as field prefills
    const RESERVED_PARAMS = new Set(['contact', 'confirm', 'code', 'rep', 'list', 'ticket', 'form', 'department', 'content', 'creator', 'site', 'filterContact', 'filterContactName', 'lead']);
    const urlPrefills = {};
    urlParams.forEach((value, key) => {
      if (!RESERVED_PARAMS.has(key)) urlPrefills[key] = value;
    });
    //embed prefills (url params take precedence)
    if (vwParams && vwParams.prefills) Object.entries(vwParams.prefills).forEach(([k, v]) => { if (!(k in urlPrefills)) urlPrefills[k] = v; });

    const params = {
      creator_id: creator_id,
      content_id: content_id,
      site_id: site_id,
      ticket_id: ticket_id,
      form: form,
      department: department,
      lead: lead,
      prefills: Object.keys(urlPrefills).length ? JSON.stringify(urlPrefills) : '',
    };

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/contactCheck serverCall",
        props.callURL,
        params,
        vwParams
      );

    this.setState({
      loading: true,
      error: false,
      timedOut: false,
      info: this.txt("Checking login and contact info ..."),
    });

    axios.defaults.withCredentials = true;
    axios
      .post(props.callURL, qs.stringify(params), this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverError.bind(this));

    this.serverCalled = true;
  }

  serverProcess(response) {
    if (this.devMode)
      console.log(
        "VideoWhisper/screens/contactCheck serverProcess:",
        response,
        this.state
      );

    //ajax
    if (!response.data) {
      this.setState({
        loading: false,
        error: true,
        timedOut: false,
        info: this.txt("Server returned no data. Please retry."),
      });
    } else {
      if (response.data.contact)
        this.props.appStateUpdate({
          contact: response.data.contact,
          confirm: response.data.contact.pin,
          contact_id: response.data.contact.id,
        });

      if (response.data.session)
        this.props.appStateUpdate(
          {
            contactCheck: true,
            session: response.data.session,
            config: response.data.config,
            language: response.data.config.language, 
            flag: response.data.config.flag,
            lead: response.data.lead || null,
            form: response.data.lead?.form_name || undefined,
          },
          { screen: true }
        );

      if (response.data.balance)
        this.props.appStateUpdate({ balance: response.data.balance });

      if (response.data.error)
        this.setState({
          loading: false,
          error: true,
          info: response.data.info,
        });
      else this.setState({ loading: false, error: false, timedOut: false });
    }
  }

  serverError(error) {
    console.log("VideoWhisper/screens/contactCheck serverError:", error);
    const errorInfo = this.getErrorInfo(error);
    this.setState({
      loading: false,
      error: true,
      timedOut: errorInfo.timedOut,
      info: errorInfo.message,
    });
  }

  render() {
    this.devMode = this.props.appState.devMode;

    if (!this.serverCalled) this.serverCall();

    return (
      <div className="layoutFull">
        {this.state.loading ? (
          <>
            <Loader active inline className="slow red" />
            <br />
            {this.state.info}
          </>
        ) : (
          <>
            {this.state.info}
            {this.state.error ? (
              <Message negative>
                <Message.Header>
                  {this.state.timedOut
                    ? this.txt("Connection timed out")
                    : this.txt("Could not load support session")}
                </Message.Header>
                <p>{this.state.info}</p>
                <Button
                  type="button"
                  size="small"
                  onClick={() => this.serverCall()}>
                  <Icon name="redo" /> {this.txt("Retry")}
                </Button>
                <Button
                  type="button"
                  size="small"
                  onClick={this.continueWithoutCheck}>
                  <Icon name="arrow right" /> {this.txt("Continue")}
                </Button>
              </Message>
            ) : (
              ""
            )}
          </>
        )}
      </div>
    );
  }
}
