import {useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import PopupContainer from "../../container";
import Input from "../../../fields/input";
import Dropdown from "../../../fields/dropdown";
import Button from "../../../button/_";
import {CreateLeadColumn} from "../../../../rest/leads";
import {handleError, handleSuccess} from "../../../../helpers/notifications";
import {required, validate} from "../../../../../validations";

const DATA_TYPE_OPTIONS = [
    {
        label: __("Text", 'limb-chatbot'),
        value: 'text'
    },
    {
        label: __("Email", 'limb-chatbot'),
        value: 'email'
    },
];

export default function AddLeadField({close, onSuccess, notifications}) {
    const [label, setLabel] = useState('');
    const [dataType, setDataType] = useState('text');
    const [labelError, setLabelError] = useState(false);
    const [saving, setSaving] = useState(false);

    const handleSave = async () => {
        // Validate label
        const labelValidation = validate(label, [required]);
        if (!labelValidation.valid) {
            setLabelError(labelValidation.message);
            return;
        }

        setSaving(true);
        try {
            const newField = await CreateLeadColumn({
                data_type: dataType,
                label: label.trim()
            });

            handleSuccess(notifications?.set, {
                title: __("Lead field created successfully.", 'limb-chatbot'),
            });

            if (onSuccess) {
                onSuccess(newField);
            }
            close();
        } catch (e) {
            handleError(e, notifications?.set, {
                title: __("Could not create lead field.", 'limb-chatbot'),
                description: e?.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
        } finally {
            setSaving(false);
        }
    };

    return (
        <PopupContainer
            title={__("Add Lead Field", 'limb-chatbot')}
            description={__("Create a new column in the Leads table", 'limb-chatbot')}
            close={close}
            loading={saving}
            footer={
                <>
                    <Button
                        type="secondary"
                        label={__("Cancel", 'limb-chatbot')}
                        onClick={close}
                        disabled={saving}
                    />
                    <Button
                        type="primary"
                        label={__("Save", 'limb-chatbot')}
                        onClick={handleSave}
                        disabled={saving || Boolean(labelError)}
                    />
                </>
            }
        >
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Dropdown
                        value={dataType}
                        setValue={setDataType}
                        options={DATA_TYPE_OPTIONS}
                        placeholder={__("Data type", 'limb-chatbot')}
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={label}
                        setValue={setLabel}
                        placeholder={__("Label", 'limb-chatbot')}
                        autofocus
                        validate={(value) => {
                            const validation = validate(value, [required]);
                            setLabelError(!validation.valid ? validation.message : false);
                            return validation.valid;
                        }}
                        errorMessage={labelError}
                    />
                </div>
            </div>
        </PopupContainer>
    );
}
