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 } from 'semantic-ui-react'

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

import { trackConfiguredSupportEvent } from "../analytics";

export default class ContactConfirm 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 = {
		 info: 'Confirming contact..',
		 confirmed: false,
		 found: false,
		 confirmation: '',
		 loading: true,
		 error: '',
		 timedOut: false,
	 	};
	 
	}
		
	serverCall(confirmOverride = '') {
		const { props } = this;
		const self = this;
	
		const confirmValue = confirmOverride || props.appState.confirm;
		const params = qs.stringify( { contact_id: props.appState.contact_id, confirm: confirmValue, ticket: props.appState.ticket_id } );
		
		if (this.devMode) console.log('VideoWhisper/screens/ContactConfirm serverCall', props.callURL, params);

		this.setState({ loading: true, error: '', timedOut: false });
	
		axios.defaults.withCredentials = true;
		axios.post(props.callURL, params, this.axiosConfig)
			.then(function (response) {
				self.serverProcess(response);
			})
			.catch(this.serverError.bind(this));
			
		this.serverCalled = true;
	}
	

	// Tracks the configured Google Ads conversion and matching GA4 event.
  trackSupportEvent(eventKey, adsSendTo, adsParams, ga4Event, ga4Params) {
    trackConfiguredSupportEvent({
      config: this.props.appState.config,
      eventKey,
      adsSendTo,
      adsParams,
      ga4Event,
      ga4Params,
      devMode: this.devMode,
      logPrefix: "VideoWhisper/screens/ContactConfirm",
    });
  }

    serverProcess(response) {
		if (this.devMode) console.log('VideoWhisper/screens/ContactConfirm 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;
			}

		const { props } = this;
		
		if (data.info) this.setState({info: data.info, confirmed: data.confirmed, found: data.found, loading: false, error: '', timedOut: false });
		else this.setState({ loading: false, error: '', timedOut: false, confirmed: data.confirmed, found: data.found });

		if (data.confirmed) 
		{
			this.trackSupportEvent('contactConfirm', props.appState.config?.gtag?.contactConfirm, {
				'event_category': 'VideoWhisper Support',
				'event_label': 'Contact Confirmed',
				'value': 10
				}, 'contact_confirm', {
				'event_category': 'conversion',
				'event_label': 'Contact Confirmed',
				'value': 10
				});

			let stateUpdate = {contactConfirmed: true, contact: data.contact, session: data.session};
			if (data.ticket) 
				{
					stateUpdate.ticket_id = data.ticket; //ticket also got opened
					stateUpdate.pin = data.pin; //ticket access pin
				
					this.trackSupportEvent('conversation', props.appState.config?.gtag?.conversation, {
							'event_category': 'VideoWhisper Support',
							'event_label': 'New Conversation',
							'value': 20
							}, 'conversation_open', {
							'event_category': 'conversion',
							'event_label': 'New Conversation',
							'value': 20
							});
				}

			if (data.gtag) //track all properties as gtag.[formname][gtagvalue]
				{
					Object.keys(data.gtag).forEach((key) => {
						this.trackSupportEvent('formSubmit', data.gtag[key], {
							'event_category': 'VideoWhisper Support',
							'event_label': 'Form ' + key,
							'value': 10
							}, 'form_submit', {
							'event_category': 'conversion',
							'event_label': 'Form ' + key,
							'form_name': key,
							'value': 10
							});
					});
				}

			this.props.appStateUpdate(stateUpdate, {screen: true});	
		} 

	}

	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 confirm contact. Please retry.'),
		};
	}
	
	serverError(error) {	
		console.log('VideoWhisper/screens/ContactConfirm serverError:', error);
		const errorInfo = this.getErrorInfo(error);
		this.setState({
			loading: false,
			error: errorInfo.message,
			timedOut: errorInfo.timedOut,
		});
	}


	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;
	
		this.setState(
		  {
			[name]: value,
		  },
		); 
	
	  };

	  onSubmitConfirm = (e) => {
		e.preventDefault();
	
		if (this.devMode)
		console.log("VideoWhisper/screen/contactConfirm onSubmitConfirm", this.state);
	
		this.props.appStateUpdate({ 
		  confirm: this.state.confirmation });
		this.serverCall(this.state.confirmation);

	  };

	retryCall = () => {
		const retryConfirm = this.state.confirmation || this.props.appState.confirm;
		this.serverCall(retryConfirm);
	}
	
	
	render ()
	{
		const { state, txt, onChange } = this;
		this.devMode = this.props.appState.devMode;
		
		if (!this.serverCalled) this.serverCall();

		let retryCode = '';
		if (state.found && !state.confirmed) {
			retryCode = <Form onSubmit={this.onSubmitConfirm} key="retryForm">
			<Message icon size="small" key="retryNotice">
				<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.Field>
				<label>
				  <Icon name="key" /> {txt("Confirmation Code")}
				</label>
				<Input
				  name="confirmation"
				  placeholder={txt("Confirmation Code")}
				  value={state.confirmation}
				  onChange={onChange}
				/>
			  </Form.Field>
			  <Button type="submit" disabled={state.confirmation.length <3 || state.loading} loading={state.loading}>
				{txt("Confirm")}
			  </Button>
			</Form>      
		}
		
		return (
			<div>
				{!state.confirmed && state.loading ? <Loader active inline className="slow red" /> : '' }
				<br/>{state.info}
				{state.error ? (
					<Message negative>
						<Message.Header>
							{state.timedOut ? txt('Connection timed out') : txt('Could not confirm contact')}
						</Message.Header>
						<p>{state.error}</p>
						<Button type="button" size="small" onClick={this.retryCall}>
							<Icon name="redo" /> {txt('Retry')}
						</Button>
					</Message>
				) : ''}
				{retryCode}
			</div>
		) 
	}
}
