import React from "react";
import ReactDOM from "react-dom";
import { useEffect, useRef } 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 {
  Button,
  Checkbox,
  Form,
  Input,
  Message,
  Label,
  Icon,
  TextArea,
  Dropdown,
  Loader,
  Header,
  Modal,
  Divider,
  Segment,
} from "semantic-ui-react";

import SupportFields from "../components/SupportFields";

export default class SupportForm extends React.Component {
  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",
        "X-WP-Nonce": props.appState.session.nonce,
      },
    };

    this.state = {
      fields: {},
      form: {},
      name: "",
      email: "",
      message: "",
      agree: false,
      loaded: false,
      saved: false,
      loading: false,
      submitting: false,
      error: "",
      timedOut: false,
      lastRequest: "load",
    };
  }

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

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

  retryRequest = () => {
    if (this.state.lastRequest === "submit") this.serverSubmit();
    else this.serverUpdate();
  };

  serverUpdate = () => {
    //onSubmit
    const { props, state } = this;
    const self = this;

    const params = qs.stringify({
      contact_id: props.appState.contact.id,
      confirm: props.appState.confirm,
      site_id: props.appState.config.site_id,
      form: props.appState.form,
    });

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Form serverUpdate",
        props.callURL,
        params
      );

    this.setState({
      loading: true,
      error: "",
      timedOut: false,
      lastRequest: "load",
    });

    axios
      .post(props.callURL, params, this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverError.bind(this));

    this.serverCalled = true;
  };

  onSubmit = (e) => {
    e.preventDefault();

    if (this.devMode)
      console.log("VideoWhisper/screens/Form onSubmit", this.state);

    this.serverSubmit();
  };

  serverSubmit = () => {
    //onSubmit
    const { props, state } = this;
    const self = this;

    const params = qs.stringify({
      contact_id: props.appState.contact.id,
      confirm: props.appState.confirm,
      site_id: props.appState.config.site_id,
      form: props.appState.form,
      fields: state.fields,
    });

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/Form serverSubmit",
        props.callURL,
        params
      );

    this.setState({
      submitting: true,
      error: "",
      timedOut: false,
      lastRequest: "submit",
    });

    axios
      .post(props.callURL, params, this.axiosConfig)
      .then(function (response) {
        self.serverProcess(response);
      })
      .catch(this.serverError.bind(this));
  };

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

    const data = response.data;

    if (!data) {
      this.setState({
        loading: false,
        submitting: false,
        error: this.txt("Server returned no data. Please retry."),
        timedOut: false,
      });
      return;
    }

    if (data.contact)
      if (!this.props.appState.contact.id)
        this.props.appStateUpdate({ contact: data.contact }); //update app contact if not present

    if (data.form) this.setState({ form: data.form });

    if (data.info) this.setState({ info: data.info });

    if (!this.state.loaded) this.setState({ loaded: true });

    this.setState({
      loading: false,
      submitting: false,
      error: "",
      timedOut: false,
    });

    this.updating = false;
  }

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

    this.updating = false;
  }

  txt = (text) => {
    //handle text translations from appState.config
    const { props } = this;
    if (!props.appState.config) return text;
    if (!props.appState.config.text) return text;

    if (text in props.appState.config.text)
      return props.appState.config.text[text];
    return text;
  };

  render() {
    const { state, onChange, props, txt } = this;

    //access:load
    if (!this.serverCalled)
      if (props.appState.contact_id && props.appState.confirm)
        this.serverUpdate();

    if (!state.loaded || !state.form)
      return (
        <div className="layoutFull" key="layoutContact">
          <Segment>
            {state.loading || (!state.loaded && !state.error) ? (
              <>
                <Icon loading name="spinner" /> {txt("Loading form...")}
              </>
            ) : (
              <>
                {state.error ? (
                  <Message negative>
                    <Message.Header>
                      {state.timedOut
                        ? txt("Connection timed out")
                        : txt("Could not load form")}
                    </Message.Header>
                    <p>{state.error}</p>
                    <Button type="button" size="small" onClick={this.retryRequest}>
                      <Icon name="redo" /> {txt("Retry")}
                    </Button>
                  </Message>
                ) : (
                  ""
                )}
              </>
            )}
            {state.info ? <Message>{state.info}</Message> : ""}
          </Segment>
        </div>
      );
    else
    if (state.form.filled && state.form.done)
      return (
        <div className="layoutFull" key="layoutForm">
           <Form>
            <Form.Field inline>
              <Label key="name">
                <Icon name="user" /> {props.appState.contact.name}{" "}
              </Label>
              <Label key="email">
                <Icon name="mail" /> {props.appState.contact.contact}{" "}
              </Label>
            </Form.Field>
            <Divider horizontal />
              <Header size="small">
                <Icon name="write" size="small" />
                {props.appState.form}
              </Header>
          <Segment>
            <p>{state.form.done}</p>
            <Button icon href={state.form.doneUrl}>
            <Icon name="arrow circle right" />
            </Button>
          </Segment>
          </Form>
        </div>
      );  
       else 
      return (
        <div className="layoutFull" key="layoutForm">
          <Form onSubmit={this.onSubmit}>
            <Form.Field inline>
              <Label key="name">
                <Icon name="user" /> {props.appState.contact.name}{" "}
              </Label>
              <Label key="email">
                <Icon name="mail" /> {props.appState.contact.contact}{" "}
              </Label>
            </Form.Field>
            <Divider horizontal>
              <Header size="small">
                <Icon name="write" size="small" />
                {props.appState.form}
              </Header>
            </Divider>
            <Form.Field>
              <small>{state.form.instructions}</small>
            </Form.Field>
            <SupportFields
              appState={props.appState}
              upState={state}
              upStateUpdate={(params) => this.setState(params)}
              key="formFields"
              fields={state.form.fields}
            />
            {state.form.terms?( <Form.Field><small>{state.form.terms}</small></Form.Field> ):""}   
            <Button type="submit" disabled={state.submitting} loading={state.submitting}>{txt("Save")}</Button>
            {state.submitting ? (
              <Message icon>
                <Icon name="spinner" loading />
                <Message.Content>{txt("Saving form...")}</Message.Content>
              </Message>
            ) : (
              ""
            )}
            {state.error ? (
              <Message negative>
                <Message.Header>
                  {state.timedOut ? txt("Connection timed out") : txt("Could not save form")}
                </Message.Header>
                <p>{state.error}</p>
                <Button type="button" size="small" onClick={this.retryRequest}>
                  <Icon name="redo" /> {txt("Retry")}
                </Button>
              </Message>
            ) : (
              ""
            )}
            {state.info ? <Message>{state.info}</Message> : ""}
          </Form>
        </div>
      );
  }
}
