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 {
  Button,
  Checkbox,
  Form,
  Input,
  Message,
  Icon,
  Divider,
  Header,
  Segment,
  Label,
  Dropdown,
  TextArea,
  Flag,
  Modal
} from "semantic-ui-react";

import isEmail from "validator/lib/isEmail";

import SupportFields from "../components/SupportFields";
import { executeRecaptchaV3 } from "../recaptcha";
import { trackConfiguredSupportEvent } from "../analytics";

export default class ContactNew extends React.Component {
  static propTypes = {
    appState: PropTypes.object.isRequired,
    appStateUpdate: PropTypes.func.isRequired,
    callURL: PropTypes.string.isRequired,
    confirmURL: PropTypes.string,
  };

  resendCooldownSeconds = 120; //2 minutes before Resend becomes available

  //Test confirm: ?contact=23&confirm=HJD6F9&form=Web#vws

  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 = {
      name: props.appState.lead?.name || "",
      email: props.appState.lead?.email || "",
      agree: false,
      validated: false,
      created: false,
      created_contact: 0,
      created_ticket: 0,
      confirmation: "",
      info: "",
      validationInfo: "",
      form: props.appState.form,
      department_id: props.appState.lead?.department_id || 0,
      fields: props.appState.lead?.fields || {},
      language: props.appState.language,
      flag: props.appState.flag,
      message: "",
      loading: false,
      error: "",
      timedOut: false,
      trackedEvents: {},
      resendAvailableAt: 0,
      resendCountdown: 0,
      resending: false,
      resendInfo: "",
      resent: false,
    };
  }

  componentWillUnmount() {
    if (this.resendTimer) clearInterval(this.resendTimer);
  }

  startResendCountdown = () => {
    const resendAvailableAt = Date.now() + this.resendCooldownSeconds * 1000;
    this.setState({ resendAvailableAt, resendCountdown: this.resendCooldownSeconds });

    if (this.resendTimer) clearInterval(this.resendTimer);
    this.resendTimer = setInterval(() => {
      const remaining = Math.max(0, Math.ceil((this.state.resendAvailableAt - Date.now()) / 1000));
      this.setState({ resendCountdown: remaining });
      if (remaining <= 0) clearInterval(this.resendTimer);
    }, 1000);
  };

  resendConfirmation = () => {
    const { props, state } = this;

    if (!props.confirmURL || !state.created_contact) return;

    this.setState({ resending: true, resendInfo: "", error: "" });

    axios
      .post(
        props.confirmURL,
        qs.stringify({ contact_id: state.created_contact, resend: 1 }),
        this.axiosConfig
      )
      .then((response) => {
        const data = response.data || {};
        this.setState({
          resending: false,
          resent: true,
          resendInfo:
            data.info ||
            this.txt("Confirmation email resent. Please check your Inbox (and Spam/Updates folders)."),
        });
      })
      .catch((error) => {
        const errorInfo = this.getErrorInfo(error);
        this.setState({ resending: false, resendInfo: errorInfo.message });
      });
  };

  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;
  };

  onChange = (event, data) => {
    const value = data.type === "checkbox" ? data.checked : data.value;
    const name = data.name;

    /*
    if (this.devMode)
      console.log(
        "VideoWhisper/screens/contactNew onChange",
        name,
        value,
        event
      );
*/
    this.setState(
      {
        [name]: value,
      },
      () => this.validation()
    ); //validate AFTER

  };

  validation() {
    const { props, state } = this;

    //validation
    let validationInfo = "";
    const emailDomain = state.email.includes("@")
      ? state.email.split("@").pop().toLowerCase()
      : "";
    const emailDotCount = (state.email.match(/\./g) || []).length;
    const emailMaxDots = Number(props.appState.config?.emailMaxDots ?? 0);
    const restrictedNameWords = Array.isArray(props.appState.config?.restrictedContactNameWords)
      ? props.appState.config.restrictedContactNameWords
      : [];
    const lowerName = state.name.toLowerCase();
    const restrictedNameWord = restrictedNameWords.find(
      (word) => word && lowerName.includes(String(word).toLowerCase())
    );

    var valid = true;

    if (!this.state.agree) 
    {
      valid = false;
      validationInfo = this.txt("Check Agree to Terms and Conditions required.") + " ";
    }

    if (!isEmail(this.state.email)) 
    {
      valid = false;
      if (state.email) validationInfo = this.txt("Invalid email.") + " ";
      else validationInfo = this.txt("Email required.") + " ";
    }

    if (props.appState.config) if (props.appState.config.emailsUnsupported)
      if (emailDomain && props.appState.config.emailsUnsupported.includes(emailDomain))
      {
        valid = false;
        validationInfo = this.txt("Unsupported email provider") + ": " + emailDomain + " ";
      }

    if (emailMaxDots > 0 && emailDotCount > emailMaxDots)
    {
      valid = false;
      validationInfo = this.txt("Email address contains too many dots.") + " " + emailDotCount + "/" + emailMaxDots + " ";
    }

    if (this.state.name.length < 3) 
    {
      valid = false;
      validationInfo = this.txt("At least 3 characters name required.") + " ";
    }

    if (restrictedNameWord)
    {
      valid = false;
      validationInfo = this.txt("Name contains a restricted word.") + " " + restrictedNameWord + " ";
    }

    /*
    if (this.devMode)
      console.log(
        "VideoWhisper/screens/contactNew validation",
        valid,
        this.state.agree,
        this.state.validated
      );
	  */
    if (valid !== state.validated || validationInfo != state.validationInfo) this.setState({ validated: valid, validationInfo: validationInfo });
  }

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

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

    this.serverCall();
  };

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

    if (this.devMode)
    console.log("VideoWhisper/screens/contactNew onSubmitConfirm", this.state);
 
    this.props.appStateUpdate({ 
      contact_id: this.state.created_contact, 
      ticket_id: this.state.created_ticket, 
      confirm: this.state.confirmation, 
      screen: 'contactConfirm' });
  };

  serverCall = async () => {
    const { props, state } = this;

    if (this.devMode)
      console.log(
        "VideoWhisper/screens/contactNew serverCall",
        props.callURL,
        state
      );

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

    try {
      const recaptchaToken = await executeRecaptchaV3(
        props.appState.config,
        "contact_new"
      );
      const requestData = {
        ...state,
        lead_token: props.appState.lead?.token || "",
        recaptcha_token: recaptchaToken,
      };

      const response = await axios.post(
        props.callURL,
        qs.stringify(requestData),
        this.axiosConfig
      );
      this.serverProcess(response);
    } catch (error) {
      this.serverError(error);
    }

    this.serverCalled = true;
  };

     	// Tracks the configured Google Ads conversion and matching GA4 event.
       trackSupportEvent(eventKey, adsSendTo, adsParams, ga4Event, ga4Params, eventState = '') {
        if (eventState && this.state.trackedEvents[eventState]) return;

        trackConfiguredSupportEvent({
          config: this.props.appState.config,
          eventKey,
          adsSendTo,
          adsParams,
          ga4Event,
          ga4Params,
          devMode: this.devMode,
          logPrefix: "VideoWhisper/screens/contactNew",
          onSent: () => {
            if (!eventState) return;
            this.setState((state) => ({
              trackedEvents: {
                ...state.trackedEvents,
                [eventState]: true,
              },
            }));
          },
        });
      }

  serverProcess(response) {

    const { props } = this;

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

    const data = response.data;

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

    if (data.created)
    this.trackSupportEvent('contactNew', props.appState.config?.gtag?.contactNew, {
      'event_category': 'VideoWhisper Support',
      'event_label': 'New Contact',
      'value': 1
      }, 'contact_submit', {
      'event_category': 'conversion',
      'event_label': 'Contact New',
      'value': 1
      });  

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

    if (data.session) this.props.appStateUpdate({ session: data.session }, {});

    if (data.info) this.setState({ created: data.created, created_contact: data.contact, info: data.info, created_ticket: data.ticket });

    if (data.created) this.startResendCountdown();
  }

  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 submit contact details. Please retry."),
    };
  }

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


  languageModalClose = () => this.setState({ languageModalShow: false })
   onLanguageButton = () => this.setState({ languageModalShow: true});

  language2flag(lang){
    const flags = { 'en-us':'us', 'en-gb':'gb', 'pt-br':'br', 'pt-pt':'pt', 'zh':'cn', 'ja':'jp', 'el':'gr', 'da':'dk', 'ko':'kr', 'nb':'no' };
    if (flags[lang]) return flags[lang];
    return lang;
  }

  onLanguageChange(event, data) {

    if (this.devMode)  console.log('VideoWhisper/screents/contactNew onLanguageChange', data, event);

    this.setState({
      language: data.value,
      flag: this.language2flag(data.value),
      languageModalShow: false,
  });

    this.props.appStateUpdate( { language : data.value, flag: this.language2flag(data.value) } );
 }

//apply url prefill values to a fields object (keyed by field name)
  componentDidMount()
 {
  if (this.devMode)
    console.log("VideoWhisper/screens/contactNew componentDidMount", this.props);

  const { props } = this;

  if (!this.state.department_id && this.props.appState.config.departmentDefault)
    this.setState({
      department_id: this.props.appState.config.departmentDefault,
    });

  if (props.appState.form) this.trackSupportEvent('formView', props.appState.config.form?.gtagView, {
    'event_category': 'VideoWhisper Support',
    'event_label': 'Form View ' + props.appState.form,
    'value': 0.1
    }, 'form_view', {
    'event_category': 'engagement',
    'event_label': 'Form View ' + props.appState.form,
    'form_name': props.appState.form,
    'value': 0.1
    }, 'formView' + props.appState.form);  

  this.trackSupportEvent('contactView', props.appState.config?.gtag?.contactView, {
    'event_category': 'VideoWhisper Support',
    'event_label': 'Contact View',
    'value': 0.1
    }, 'contact_view', {
    'event_category': 'engagement',
    'event_label': 'Contact View',
    'value': 0.1
    }, 'contactView');
 }

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


    var formCode = "";
    if (props.appState.form && props.appState.config.form) {
      formCode = (
        <div key="contactForm">
          <Divider horizontal>
            <Header size="small">
              <Icon name="write" size="small" />
              {props.appState.form}
            </Header>
          </Divider>
          <Form.Field>
            <small>{props.appState.config.form.instructions}</small>
          </Form.Field>
          <SupportFields
            appState={props.appState}
            upState={state}
            upStateUpdate={(params) => this.setState(params)}
            key="formFields"
            fields={props.appState.config.form.fields}
          />
            {props.appState.config.form.terms?( <Form.Field><small>{props.appState.config.form.terms}</small></Form.Field> ):""}   
        </div>
      );
    }

    var departmentSelectCode = "";
    var departmentCode = [];
    var topicCode = "";

    if (!props.appState.form && props.appState.config.registerConversation)
    {
      
      var contextCode = "";

      if (
        props.appState.config.context.content ||
        props.appState.config.context.creator
      )
        contextCode = (
          <Form.Field inline>
            {" "}
            {props.appState.config.context.content ? (
              <>
                {" "}
                <Label basic>
                  <Icon name="file" /> {props.appState.config.context.content}
                </Label>
              </>
            ) : (
              ""
            )}
            {props.appState.config.context.url ? (
              <>
                <Button
                  basic
                  compact
                  size="tiny"
                  icon
                  href={props.appState.config.context.url}
                  target="Content">
                  <Icon name="linkify" />{" "}
                </Button>
              </>
            ) : (
              ""
            )}{" "}
            {props.appState.config.context.creator ? (
              <>
                {" "}
                <Label basic>
                  <Icon name="user" /> {props.appState.config.context.creator}
                </Label>
              </>
            ) : (
              ""
            )}
          </Form.Field>
        );

      if (props.appState.config.departments)
      {

      departmentSelectCode =(
        <Form.Group key="Department">
        <Form.Field>
        <label>
                <Icon name="box" /> {txt("Department")}
              </label>
          <Dropdown
            name="department_id"
            placeholder="Select Department..."
            aria-label={txt("Department")}
            selection
            options={props.appState.config.departments}
            value={state.department_id}
            onChange={onChange}
          />
        </Form.Field>
        {contextCode}
      </Form.Group>);

      //department fields
      var selectedDepartment = null; //selected department
      if (state.department_id && state.department_id > 0)
        if (props.appState.config.departments) {
          selectedDepartment = props.appState.config.departments.find(
            (item) => item.value == state.department_id
          );

          if (selectedDepartment)
          {
            if (selectedDepartment.instructions) departmentCode.push(<Message size="small" key="instructions">{selectedDepartment.instructions}</Message>);

            if (selectedDepartment.fields) {
              departmentCode.push(
                <SupportFields
                  appState={props.appState}
                  upState={state}
                  upStateUpdate={(params) => this.setState(params)}
                  key="DepartmentFields"
                  fields={selectedDepartment.fields}
                />
              );
            }
          }
        }

        if (selectedDepartment)
        {
//language
var languageModalCode = '';
var codeLanguage = '';

if (props.appState.config.multilanguage && props.appState.config.languages) {

  codeLanguage = ( <Form.Field key="languageButton"> <Button compact icon type="button" data-tooltip={txt('My Language')} onClick={this.onLanguageButton} inverted={props.appState.config.darkMode}><Flag name={props.appState.flag} /></Button>   </Form.Field>);

  const field = props.appState.config.languages;

   languageModalCode = (
    <Modal key='languageModal' closeIcon
    open={state.languageModalShow}
    onClose={this.languageModalClose}
    size='small' basic={props.appState.config.darkMode}
  >
    <Header icon='flag' content={txt("My Language")} />
    <Modal.Content>
    <Form>
    <Dropdown name={field.name} selection compact fluid
           className={props.appState.config.className + " v-select"} data-position="right center" 
           value={props.appState.language} options={field.options} flag={props.appState.flag}
           onChange={(e, data)=>this.onLanguageChange(e, data)} />
      <div>{field.details}</div>
    </Form>
    </Modal.Content>
  </Modal>
    );        
}

        topicCode = (
          <>
          <Form.Field key="message">
               <label>
                  <Icon name="comment" /> {txt("Topic")}
                </label>
          <TextArea
            name="message"
            placeholder={txt("Describe the topic, in brief. You can add more details after opening conversation.")}
            onChange={onChange}
            value={state.message}></TextArea> 
        </Form.Field>
        {codeLanguage}     
        {languageModalCode}
        </>
        );

        }

        //departments
      }

  }
    
  

    if (!state.created)
      return (
        <div className="layoutFull" key="layoutContact">
          <Form onSubmit={this.onSubmit}>
            {props.appState.form ? (
              <Header key="contactHeader">
                {" "}
                <Icon name="write" size="small" />{" "}
                {txt("Provide your contact details, to send form.")}{" "}
              </Header>
            ) : (
              <Header key="formHeader">
                <Icon name="comments" size="small" />
                {txt(
                  "Provide your contact details, to open conversation."
                )}{" "}
              </Header>
            )}
            <Divider />
            <Form.Field>
              <label>
                <Icon name="user" /> {txt("Name")}
              </label>
              <Input
                name="name"
                placeholder={txt("Name")}
                value={state.name}
                onChange={onChange}
              />
            </Form.Field>
            <Form.Field>
              <label>
                <Icon name="mail" /> {txt("Email")}
              </label>
              <Input
                name="email"
                placeholder={txt("Email")}
                value={state.email}
                onChange={onChange}
              />
              <small>
                <Icon name="info circle" />{" "}
                {txt(
                  "A confirmation code will be sent to this email address — it is required to complete registration."
                )}
              </small>
            </Form.Field>

            {formCode}
            {departmentSelectCode}
            {departmentCode}
            {topicCode}

            <Form.Field>
              <Checkbox
                id="agree"
                name="agree"
                label={txt("I agree to the Terms and Conditions")}
                checked={state.agree ? true : false}
                onChange={onChange}
              /> &nbsp;
              <Button icon size="tiny" compact href={props.appState.config.termsURL} target="_terms" aria-label={txt("Read Terms and Conditions")}>
            <Icon name="external" aria-hidden="true" />
             </Button>    
            </Form.Field>
            <Button
              disabled={!state.validated || state.created || state.loading}
              loading={state.loading}
              type="submit">
              {txt("Submit")}
            </Button>
            {state.info ? <Message>{state.info}</Message> : ""}
            {state.loading ? (
              <Message icon>
                <Icon name="spinner" loading />
                <Message.Content>{txt("Submitting contact details...")}</Message.Content>
              </Message>
            ) : (
              ""
            )}
            {state.error ? (
              <Message negative>
                <Message.Header>
                  {state.timedOut
                    ? txt("Connection timed out")
                    : txt("Could not submit contact details")}
                </Message.Header>
                <p>{state.error}</p>
                <Button type="button" size="small" onClick={this.serverCall}>
                  <Icon name="redo" /> {txt("Retry")}
                </Button>
              </Message>
            ) : (
              ""
            )}
            {state.validationInfo ? (
              <Message >{state.validationInfo}</Message>
            ) : (
              ""
            )}
          </Form>
        </div>
      );
    else           //include form to submit confirmation code for contact
      return (
        <div className="layoutFull" key="layoutContact">
          <Segment>
            {" "}
            <Icon name="check circle" />{" "}
            {state.info ? <Message>{state.info}</Message> : ""}
          </Segment>
          <Message icon size="small">
            <Icon name="mail outline" />
            <Message.Content>
              <Message.Header>{txt("Can't find the confirmation email?")}</Message.Header>
              {txt(
                "Please also check your Spam folder, or other categories like Updates, in your email client. Confirmation emails can sometimes take a while to arrive, especially when using email forwarders."
              )}
            </Message.Content>
          </Message>
          <Form onSubmit={this.onSubmitConfirm}>
          <Form.Field>
              <label>
                <Icon name="key" /> {txt("Confirmation Code From Email")}
              </label>
              <Input
                name="confirmation"
                placeholder={txt("Confirmation Code From Email")}
                value={state.confirmation}
                onChange={onChange}
              />
            </Form.Field>
            <Button type="submit" disabled={state.confirmation.length <3}>
              {txt("Confirm")}
            </Button>
          </Form>
          <Divider hidden />
          {!state.resent ? (
            <Button
              type="button"
              basic
              size="small"
              loading={state.resending}
              disabled={state.resending || state.resendCountdown > 0}
              onClick={this.resendConfirmation}
              inverted={props.appState.config.darkMode}>
              <Icon name="redo" />{" "}
              {state.resendCountdown > 0
                ? txt("Resend Confirmation Email") + " (" + state.resendCountdown + "s)"
                : txt("Resend Confirmation Email")}
            </Button>
          ) : (
            <Message size="small">
              {txt(
                "If you still can't find the confirmation email, you can try registering again with a different email address."
              )}
            </Message>
          )}
          {state.resendInfo ? <Message size="small">{state.resendInfo}</Message> : ""}
        </div>
      );
  }
}
