import { Grid, Dropdown, createElement, createCheckbox, Popup, showAlert } 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;
        }
    }

    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('P_CR_TEXT', 'Text') },
            { value: '1', text: r('P_CR_EMAIL', 'Email') },
            { value: '2', text: r('P_CR_PHONE', '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('P_WO_ADDCONTACTRECORD', 'Add Contact Record') : r('P_WO_EDITCONTACTRECORD', '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('P_WO_WORKORDERONLY', '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('P_WO_CANCEL', 'Cancel'),
                // tabIndex: tabIndex + 9
            }
        );
        const popup = new Popup({
            onMasking: this._var.option.onMasking,
            title: c == null ? r('P_CR_ADDCONTACT', 'Add Contact') : r('P_CR_EDITCONTACT', '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('P_CR_CONTACTNAME_COLON', 'Contact Name:')),
                    contactName
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('P_CR_CONTACTPREFERENCES_COLON', 'Contact Preferences:')),
                    preferences.create()
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('P_CR_EMAILADDRESS_COLON', 'Email Address:')),
                    contactEmail
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('P_WO_MOBILE_COLON', 'Mobile:')),
                    contactMobile
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('P_CR_OPTOUT_COLON', 'Opt Out:')),
                    checkOpt
                ),
                createElement('div', 'setting-item',
                    createElement('span', 'setting-label', r('P_CR_NOTES_COLON', '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);
        setTimeout(() => 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('P_CR_ADDCONTACT', 'Add Contact') : r('P_CR_EDITCONTACT', 'Edit Contact');
        if (nullOrEmpty(name)) {
            showAlert(title, r('P_CR_CONTACTNAMECANNOTBEEMPTY', 'Contact Name cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactName.focus());
            return null;
        }
        if ((pref == 0 || pref == 2) && nullOrEmpty(phone)) {
            showAlert(title, r('P_CR_MOBILECANNOTBEEMPTY', 'Mobile cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactMobile.focus());
            return null;
        }
        if (pref == 1 && nullOrEmpty(email)) {
            showAlert(title, r('P_CU_EMAILCANNOTBEEMPTY', 'Email cannot be empty.'), 'warn')
                .then(() => this._var.refs.contactEmail.focus());
            return null;
        }
        if (!nullOrEmpty(email) && !isEmail(email)) {
            showAlert(title, r('P_CR_EMAILISNOTAVALIDEMAILADDRESS', '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;
        }
    }

    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('P_WO_OK', '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('P_WO_CANCEL', '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("P_CR_CONTACTNAME", "Contact Name"), width: 100 },
            { key: 'Email', caption: r("P_CR_CONTACTEMAIL", "Contact Email"), css: { 'width': 180, 'text-align': 'left' } },
            { key: 'MobilePhoneDisplayText', caption: r("P_CR_CONTACTMOBILE", "Contact Mobile"), width: 130 },
            { key: 'ContactPreferenceStr', caption: r("P_CR_CONTACTPREFERENCES", "Contact Preferences"), width: 100 },
            { key: 'OptOut', caption: r("P_CR_OPTOUT", "Opt Out"), type: Grid.ColumnTypes.Checkbox, width: 70, enabled: false, align: 'center' },
            { key: 'Notes', caption: r("P_CR_NOTES", "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;
        }
    }
}