import { Grid, Dropdown, createElement, createCheckbox, Popup, showAlert, requestAnimationFrame } from "../../ui";
import { isEmail, nullOrEmpty, r as lang } from "../../utility";

let r = lang;

export class Contact {
    _var = {};

    constructor(option = {}) {
        this._var.option = option;
        const getText = option?.getText;
        if (typeof getText === 'function') {
            r = getText;
        } else if (typeof GetTextByKey === 'function') {
            r = GetTextByKey;
        }
    }

    async show(parent = document.body) {
        const tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)) + 3;

        const c = this._var.option.contact;
        const contactName = createElement('input', input => {
            input.type = 'text';
            input.className = 'ui-input';
            input.tabIndex = tabIndex + 1;
            input.maxLength = 200;
            input.autocomplete = 'off';
        });
        const preferences = new Dropdown({ tabIndex: tabIndex + 2 });
        preferences.source = [
            { value: '0', text: r('FLTL_02915', 'Text') },
            { value: '1', text: r('FLTL_01089', 'Email') },
            { value: '2', text: r('FLTL_02194', 'Phone') }
        ];
        const contactEmail = createElement('input', input => {
            input.type = 'email';
            input.className = 'ui-input';
            input.tabIndex = tabIndex + 3;
            input.maxLength = 100;
            input.autocomplete = 'off';
        });
        const contactMobile = createElement('input', input => {
            input.type = 'tel';
            input.className = 'ui-input';
            input.tabIndex = tabIndex + 4;
            input.maxLength = 50;
            input.autocomplete = 'off';
        });
        const checkOpt = createCheckbox({ tabIndex: tabIndex + 5 });
        const contactNotes = createElement('textarea', txt => {
            txt.className = 'ui-text';
            txt.tabIndex = tabIndex + 6;
            txt.maxLength = 2000;
            txt.style.height = '100px';
        });
        const buttons = [];
        if (this._var.option.company) {
            buttons.push({
                text: c == null ? r('FLTL_00100', 'Add Contact Record') : r('FLTL_01042', 'Edit Contact Record'),
                // tabIndex: tabIndex + 7,
                trigger: () => {
                    const item = this.prepare();
                    if (item == null) {
                        return false;
                    }
                    item.SaveToCustomer = 1;
                    if (typeof this._var.option.onSave === 'function') {
                        return this._var.option.onSave.call(this, item, 'customerrecord');
                    }
                }
            });
        }
        buttons.push(
            {
                text: r('FLTL_03348', 'Work Order Only'),
                // tabIndex: tabIndex + 8,
                trigger: () => {
                    const item = this.prepare();
                    if (item == null) {
                        return false;
                    }
                    //item.Id = -1;
                    item.SaveToCustomer = 0;
                    if (typeof this._var.option.onSave === 'function') {
                        return this._var.option.onSave.call(this, item, 'workorder');
                    }
                }
            },
            {
                text: r('FLTL_00499', 'Cancel'),
                // tabIndex: tabIndex + 9
            }
        );
        const popup = new Popup({
            onMasking: this._var.option.onMasking,
            title: c == null ? r('FLTL_00099', 'Add Contact') : r('FLTL_01041', 'Edit Contact'),
            content: createElement('div', wrapper => {
                wrapper.className = 'setting-wrapper';
                wrapper.style.width = '500px';
            },
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label setting-required', r('FLTL_00640', 'Contact Name:')),
                    contactName
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('FLTL_00643', 'Contact Preferences:')),
                    preferences.create()
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('FLTL_01092', 'Email Address:')),
                    contactEmail
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('FLTL_01932', 'Mobile:')),
                    contactMobile
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('FLTL_02089', 'Opt Out:')),
                    checkOpt
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('FLTL_02017', 'Notes:')),
                    contactNotes
                )
            ),
            buttons
        })
        if (c != null) {
            contactName.value = c.Name;
            preferences.select(String(c.ContactPreference));
            contactEmail.value = c.Email;
            contactMobile.value = c.MobilePhone;
            checkOpt.querySelector('input').checked = c.OptOut;
            contactNotes.value = c.Notes;
        } else {
            preferences.select('0');
        }
        this._var.refs = {
            contactName,
            preferences,
            contactEmail,
            contactMobile,
            checkOpt,
            contactNotes
        };
        const result = await popup.show(parent);
        requestAnimationFrame(() => contactName.focus());
        return result;
    }

    prepare() {
        const name = this._var.refs.contactName.value;
        const pref = this._var.refs.preferences.selected.value;
        const email = this._var.refs.contactEmail.value;
        const phone = this._var.refs.contactMobile.value;
        const opt = this._var.refs.checkOpt.querySelector('input').checked;
        const notes = this._var.refs.contactNotes.value;
        const title = this._var.option.contact == null ? r('FLTL_00099', 'Add Contact') : r('FLTL_01041', 'Edit Contact');
        if (nullOrEmpty(name)) {
            showAlert(title, r('FLTL_00639', 'Contact Name cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactName.focus());
            return null;
        }
        if ((pref == 0 || pref == 2) && nullOrEmpty(phone)) {
            showAlert(title, r('FLTL_01929', 'Mobile cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactMobile.focus());
            return null;
        }
        if (pref == 1 && nullOrEmpty(email)) {
            showAlert(title, r('FLTL_01094', 'Email cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactEmail.focus());
            return null;
        }
        if (!nullOrEmpty(email) && !isEmail(email)) {
            showAlert(title, r('FLTL_02952', 'The email address is invalid.'), 'warn')
                .then(() => this._var.refs.contactEmail.focus());
            return null;
        }

        let contact = this._var.option.contact;
        if (contact == null) {
            contact = {};
        } else if (contact.OptOut !== opt) {
            if (opt !== false || contact.OptOut_BC === false) {
                contact.selected = !opt;
            }
        }
        contact.OldName = contact.Name;
        contact.OldMobilePhone = contact.MobilePhone;
        contact.Name = name;
        contact.ContactPreference = pref;
        contact.Email = email;
        contact.MobilePhone = phone;
        contact.OptOut = opt;
        contact.Notes = notes;
        return contact;
    }
}

export class CustomerRecordContact {
    _var = {};

    constructor(option = {}) {
        this._var.option = option;
        const getText = option?.getText;
        if (typeof getText === 'function') {
            r = getText;
        } else if (typeof GetTextByKey === 'function') {
            r = GetTextByKey;
        }
    }

    async show(title, parent = document.body) {
        // const tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)) + 3;

        const gridContainer = createElement('div', 'selcontact-grid');
        const popup = new Popup({
            onMasking: this._var.option.onMasking,
            title,
            content: createElement('div', 'selcontact-wrapper',
                gridContainer
            ),
            buttons: [
                {
                    text: r('FLTL_02057', 'OK'),
                    key: 'ok',
                    trigger: () => {
                        if (typeof this._var.option.onOk === 'function') {
                            return this._var.option.onOk.call(this, this._var.grid.source.filter(f => f.selected));
                        }
                    }
                },
                { text: r('FLTL_00499', 'Cancel'), key: 'cancel' }
            ]
        });
        const result = await popup.show(parent);
        // grid
        const grid = new Grid(gridContainer);
        grid.columns = [
            {
                key: 'selected',
                type: Grid.ColumnTypes.Checkbox,
                width: 40,
                // enabled: item => !nullOrEmpty(item.ID)
            },
            { key: 'Name', caption: r('FLTL_00637', 'Contact Name'), width: 100 },
            { key: 'Email', caption: r('FLTL_00633', 'Contact Email'), css: { 'width': 180, 'text-align': 'left' } },
            { key: 'MobilePhoneDisplayText', caption: r('FLTL_00636', 'Contact Mobile'), width: 130 },
            { key: 'ContactPreferenceStr', caption: r('FLTL_00642', 'Contact Preferences'), width: 100 },
            { key: 'OptOut', caption: r('FLTL_02084', 'Opt Out'), type: Grid.ColumnTypes.Checkbox, width: 70, enabled: false, align: 'center' },
            { key: 'Notes', caption: r('FLTL_02012', 'Notes'), width: 120 }
        ];
        grid.init();
        grid.source = this._var.option.contacts.sort(function (a, b) { return ((b.Text || b.Email) ? 1 : 0) - ((a.Text || a.Email) ? 1 : 0) });
        this._var.grid = grid;
        return result;
    }

    set source(contacts) {
        this._var.option.contacts = contacts;
        const grid = this._var.grid;
        if (grid != null) {
            this._var.grid.source = contacts;
        }
    }
}