import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { useState, useEffect, useCallback } from '@wordpress/element';
import { PanelBody, PanelRow, TextControl, SelectControl } from '@wordpress/components';
import { debounce } from "lodash";

import './editor.scss';
import { driveWorksIconColor } from './icons';

const Edit = (props) => {
    const {
        attributes: {
            serverUrl, groupAlias, embedType, projectName, driveAppAlias,
            pingInterval, formHeight, messageFormComplete, messageFormCancel,
            onComplete, onCancel
        },
        setAttributes, className
    } = props;

    const blockProps = useBlockProps({
        className: "driveworks-block-form-embed-details",
    });

    const [clientMessage, setClientMessage] = useState();
    const emptyState = "-- Not set --";
    const emptyRequired = <div>{emptyState} <span style={{ color: "#ef4444", fontWeight: "500" }}>(required)</span></div>
    const requiredMessage = <div className="field-required" style={{ color: "#ef4444" }}>Required field</div>

    const validateClientUrl = async (url) => {
        if (!url) { return; }
        const cleanUrl = url.replace(/\/$/, ""); // Strip trailing slash
        const clientLibraryUrl = cleanUrl + "/DriveWorksLiveIntegrationClient.min.js";
        const successMessage = <span style={{ color: "#059669" }}>Client library found.</span>
        const warningMessage = <span style={{ color: "#d97706" }}>Could not validate client library is present.</span>

        try {
            const response = await fetch(clientLibraryUrl, { method: "HEAD" });
            if (!response.ok) {
                setClientMessage(warningMessage);
                return;
            }

            setClientMessage(successMessage);
        } catch (error) {
            setClientMessage(warningMessage);
        }
    }
    const debouncedValidateClientUrl = useCallback(debounce(validateClientUrl, 300), []);

    useEffect(() => {
        debouncedValidateClientUrl(serverUrl);
    }, [serverUrl]);

    return (
        <div {...blockProps}>

            <InspectorControls key="setting">
                <PanelBody title="Connection Details" initialOpen={true}>
                    <PanelRow>
                        <TextControl
                            label="Integration Theme Server Url"
                            value={serverUrl}
                            help={serverUrl ? clientMessage : requiredMessage}
                            onChange={(val) => setAttributes({ serverUrl: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextControl
                            label="Group Alias"
                            value={groupAlias}
                            help={groupAlias ? "" : requiredMessage}
                            onChange={(val) => setAttributes({ groupAlias: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <SelectControl
                            label="Embed Type"
                            value={embedType}
                            style={{ lineHeight: "unset" }}
                            onChange={(val) => setAttributes({ embedType: val })}
                            options={[
                                { label: 'Project', value: 'Project' },
                                { label: 'DriveApp', value: 'DriveApp' },
                            ]}
                        />
                    </PanelRow>
                    <PanelRow>
                        {embedType == "Project" ?
                            <TextControl
                                label="Project Name"
                                value={projectName}
                                help={projectName ? "" : requiredMessage}
                                onChange={(val) => setAttributes({ projectName: val })}
                            /> : ""
                        }
                        {embedType == "DriveApp" ?
                            <TextControl
                                label="DriveApp Alias"
                                value={driveAppAlias}
                                help={driveAppAlias ? "" : requiredMessage}
                                onChange={(val) => setAttributes({ driveAppAlias: val })}
                            /> : ""
                        }
                    </PanelRow>
                </PanelBody>
                <PanelBody title="Additional Settings" initialOpen={false}>
                    <PanelRow>
                        <TextControl
                            type="number"
                            label="Ping Interval (seconds)"
                            value={pingInterval}
                            help={"(optional) Enter number in seconds e.g. '60'. Disable ping using '0' or leaving empty."}
                            onChange={(val) => setAttributes({ pingInterval: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextControl
                            label="Form Height"
                            value={formHeight}
                            help="(optional) Include unit e.g. px/em"
                            onChange={(val) => setAttributes({ formHeight: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextControl
                            label="Specification Complete Action"
                            value={onComplete}
                            help="(optional) The URL to redirect to on Specification completion. Alternatively, enter 'Restart' to start a new Specification."
                            onChange={(val) => setAttributes({ onComplete: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextControl
                            label="Specification Cancel Action"
                            value={onCancel}
                            help="(optional) The URL to redirect to on Specification cancellation. Alternatively, enter 'Restart' to start a new Specification."
                            onChange={(val) => setAttributes({ onCancel: val })}
                        />
                    </PanelRow>
                </PanelBody>
                <PanelBody title="Customize Messages" initialOpen={false}>
                    <PanelRow>
                        <TextControl
                            label="Form Completed Message"
                            value={messageFormComplete}
                            onChange={(val) => setAttributes({ messageFormComplete: val })}
                        />
                    </PanelRow>
                    <PanelRow>
                        <TextControl
                            label="Form Cancelled Message"
                            value={messageFormCancel}
                            onChange={(val) => setAttributes({ messageFormCancel: val })}
                        />
                    </PanelRow>
                </PanelBody>
            </InspectorControls>

            <div className={className}>
                <div className="block-heading">
                    {driveWorksIconColor}
                    <div>
                        <div className="block-title">DriveWorks Form Embed</div>
                        <div className="block-subtitle">Edit connection details in block settings.</div>
                    </div>
                </div>
                <table>
                    <tr>
                        <td>Server Url</td>
                        <td>{serverUrl ? serverUrl : emptyRequired}</td>
                    </tr>
                    <tr>
                        <td>Group Alias</td>
                        <td>{groupAlias ? groupAlias : emptyRequired}</td>
                    </tr>
                    {embedType == "Project" ?
                        <tr>
                            <td>Project Name</td>
                            <td>{projectName ? projectName : emptyRequired}</td>
                        </tr>
                        : ""}
                    {embedType == "DriveApp" ?
                        <tr>
                            <td>DriveApp Alias</td>
                            <td>{driveAppAlias ? driveAppAlias : emptyRequired}</td>
                        </tr>
                        : ""}
                    {pingInterval ?
                        <tr>
                            <td>Ping Interval</td>
                            <td>{pingInterval} second{pingInterval == 1 ? "" : "s"}</td>
                        </tr>
                        : ""}
                    {formHeight ?
                        <tr>
                            <td>Form Height</td>
                            <td>{formHeight}</td>
                        </tr>
                        : ""}
                    {onComplete ?
                        <tr>
                            <td>On Complete</td>
                            <td>{onComplete}</td>
                        </tr>
                        : ""}
                    {onCancel ?
                        <tr>
                            <td>On Cancel</td>
                            <td>{onCancel}</td>
                        </tr>
                        : ""}
                </table>
            </div>

        </div>
    );
}

export default Edit;
