/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';

import { PanelBody, PanelRow, SelectControl, Notice, Button, Placeholder, Spinner } from '@wordpress/components';

// Axios for Faxosaurus API calls
import axios from 'axios';

// API to grab Faxosaurus API key from settings
import apiFetch from '@wordpress/api-fetch';


import { useEffect, useState } from 'react';

import FaxosaurusFormPreview from './faxosaurus-form-preview';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit( { attributes, setAttributes}) {
	const { fxid, surveyJson } = attributes;
	const isFxidPresent = fxid != "" && fxid != null;

	const [apiError, setApiError] = useState(null);
	const [apiLoaded, setApiLoaded] = useState(false);
	const [apiKey, setApiKey] = useState(null);
	const [availableForms, setAvailableForms] = useState([]);


	useEffect(() => {
		if(!isFxidPresent) {
			return () => {}
		}
		let ignore = false;
		axios.get(`https://secure.faxosaurus.com/survey.json?fxid=${fxid}`).then(({ data }) => {
			const {survey, customQuestions} = data;
			if (!ignore) {
				setAttributes({ surveyJson: survey, customQuestions: customQuestions });
			}
		}).catch((error) => {
			let { message } = error;
			if (error.response) {
				if (error.response.status === 404) {
					message = 'Unable to find Faxosaurus form';
				}
			}
			if(error.code === 'ERR_NETWORK') {
				message = 'Network Error: Unable to connect to Faxosaurus API';
			}
			setApiError(message);
		});
		return () => {
			// Prevent ajax calls/promises from stacking up
			ignore = true;
		};
	}, [fxid]);


	useEffect(() => {
		apiFetch({ path: '/wp/v2/settings' }).then((settings) => {
			return settings
		}).then( ({faxosaurus_api_key}) => {
			setApiKey(faxosaurus_api_key);
		});
	},[]);


	useEffect(() => {
		if(apiKey == null) {
			return () => {}
		}
		axios.post(`https://faxosaurus.com/wp/auth`, { secret: apiKey }).then(({ data }) => {
			const availableForms = data.map((form) => {
				return { value: form[0], label: form[1] }
			})

			availableForms.unshift({ value: '', label: 'Select a form' });
			setApiLoaded(true);
			setAvailableForms(availableForms);
		}).catch((error) => {
			let { message } = error;
			if (error.response) {
				if (error.response.status === 402) {
					message = 'WordPress integration has been disabled on Faxosaurus. Please enable it to use this block.';
				}
			}
			if(error.code === 'ERR_NETWORK') {
				message = 'Network Error: Unable to connect to Faxosaurus API';
			}
			setApiLoaded(true);
			setApiError(message);
		});

	}, [apiKey]);

	return (
		<>
			<InspectorControls>
				<PanelBody title={ __( 'Form Settings', 'faxosaurus' ) }>
					<PanelRow>
						<fieldset>
							<Button 
								variant='primary'
								target='_blank'
								disabled={!isFxidPresent}
								href={`https://faxosaurus.com/app/forms/${fxid}/manage`} >
								Manage on Faxosaurus
							</Button>
						</fieldset>
					</PanelRow>
				</PanelBody>

			</InspectorControls>
			{apiLoaded ? (

				<div { ...useBlockProps() }>
					{apiError && (
						<Notice
						onDismiss={() => { setApiError(null) }}
						onRemove={() => { setApiError(null) }}
						politeness="polite"
						status="error">
							{apiError}
						</Notice>
					)}
					{isFxidPresent ? (
						<div>
							<FaxosaurusFormPreview surveyJson={surveyJson} />
						</div>
					) : (
						<SelectControl
							label={__('Select Form to Embed', 'faxosaurus')}
							value={ fxid }
							options={ availableForms }
							onChange={ (value) => setAttributes({ fxid: value }) }
						/>

					)}
				</div>
			): (
				<div { ...useBlockProps() }>
					<Placeholder>
						<Spinner />
					</Placeholder>
				</div>
			)}
		</>
	);
}
