import { composeDataTable } from './data-table.js';
import { posPost, applyValidationErrors } from '../lib/http.js';
import { KNOWN_PRINTER_FILTERS } from '../hardware/webusb-driver.js';

/**
 * Flatten a saved `receipt_printer` config block into the editor's form
 * fields (or sensible defaults when a terminal has no config yet).
 */
function configToForm(config) {
    const c = config || {};
    const d = c.webusb_device_descriptor || {};
    return {
        printer_mode:        c.mode || 'browser_print',
        paper_width:         c.paper_width || '80mm',
        cut_paper:           c.cut_paper !== false,
        open_drawer_on_cash: c.open_drawer_on_cash !== false,
        drawer_pin:          String(c.drawer_pin || 2),
        webusb_vendor_id:    d.vendor_id || '',
        webusb_product_id:   d.product_id || '',
        webusb_label:        (d.vendor_id && d.product_id) ? `${d.vendor_id}:${d.product_id}` : '',
    };
}

/**
 * Alpine factory for the Terminals index page.
 *
 * Trimmed sibling of `brandsPage`: same master-detail shape (list +
 * sticky editor) and the same AJAX list-swap, minus the logo upload and
 * the delete-with-move modal. A terminal delete just detaches it from
 * past sales/shifts (nullOnDelete), so a plain confirm is enough.
 */
export function terminalsPage({
    storeUrl,
    updateUrlTemplate,
    deleteUrlTemplate,
    selectUrlTemplate,
    clearSelectionUrl,
    activeTerminalId = null,
    rows = [],
    initial = null,
} = {}) {
    const blank = () => ({
        id:        null,
        store_id:  '',
        code:      '',
        name:      '',
        is_active: true,
        ...configToForm(null),
    });

    return composeDataTable(
        {
            rowsSelector:       'li[data-dt-row]',
            searchableSelector: '.term-row-name',
            initialPageSize:    25,
        },
        {
            mode:        'idle',
            form:        blank(),
            rowsById:    {},
            submitting:  false,
            togglingIds: [],

            // Which terminal THIS browser is bound to (pos_terminal_id cookie).
            activeTerminalId,
            selectingId: null,

            _rootEl: null,

            get isIdle() { return this.mode === 'idle'; },
            get isEdit() { return this.mode === 'edit' && !!this.form.id; },
            get isNew()  { return this.mode === 'new'; },
            get isTable() { return true; },

            get formAction() {
                return this.isEdit
                    ? updateUrlTemplate.replace('__ID__', this.form.id)
                    : storeUrl;
            },

            get rowMeta() {
                return this.isEdit ? this.rowsById[this.form.id] ?? null : null;
            },

            init() {
                this._rootEl  = this.$el;
                this.rowsById = Object.fromEntries(rows.map((r) => [r.id, r]));

                if (initial && typeof initial === 'object' && initial.mode) {
                    this.mode = initial.mode;
                    this.form = {
                        id:        initial.id ?? null,
                        store_id:  initial.store_id ?? '',
                        code:      initial.code ?? '',
                        name:      initial.name ?? '',
                        is_active: initial.is_active !== false,
                        ...configToForm(initial.config),
                    };
                }

                this.initDataTable();
            },

            openNew() {
                this.mode = 'new';
                this.form = blank();
            },

            openEdit(id) {
                const row = this.rowsById[id];
                if (!row) return;
                this.mode = 'edit';
                this.form = {
                    id:        row.id,
                    store_id:  row.store_id ?? '',
                    code:      row.code ?? '',
                    name:      row.name ?? '',
                    is_active: row.is_active !== false,
                    ...configToForm(row.config),
                };
            },

            /** Pair a WebUSB thermal printer — the browser remembers the
             *  grant per-origin, and we store the device descriptor so the
             *  cashier's print bridge reconnects to the same printer. */
            async pairPrinter() {
                if (!navigator.usb) {
                    this.$store.toasts.push({
                        type:    'warning',
                        message: 'WebUSB isn\'t supported in this browser. Use Chrome or Edge on desktop/Android.',
                    });
                    return;
                }
                try {
                    const device = await navigator.usb.requestDevice({ filters: KNOWN_PRINTER_FILTERS });
                    const hex = (n) => '0x' + n.toString(16).padStart(4, '0');
                    this.form.webusb_vendor_id  = hex(device.vendorId);
                    this.form.webusb_product_id = hex(device.productId);
                    this.form.webusb_label = `${device.productName || 'Printer'} (${this.form.webusb_vendor_id}:${this.form.webusb_product_id})`;
                } catch (e) {
                    // User dismissed the device picker — nothing to do.
                }
            },

            closeEditor() {
                this.mode = 'idle';
                this.form = blank();
            },

            async toggleActive(id) {
                const row = this.rowsById[id];
                if (!row || this.togglingIds.includes(id)) return;
                const next = !row.is_active;

                row.is_active    = next;
                this.togglingIds = [...this.togglingIds, id];

                const fd = new FormData();
                fd.append('_token',     document.querySelector('meta[name="csrf-token"]')?.content || '');
                fd.append('_method',    'PATCH');
                fd.append('name',       row.name ?? '');
                // Resend the existing code so the server doesn't regenerate
                // a fresh one (a blank code auto-derives on persist).
                fd.append('code',       row.code ?? '');
                fd.append('is_active',  next ? '1' : '0');
                fd.append('editing_id', id);

                const data = await this._send(updateUrlTemplate.replace('__ID__', id), fd);
                this.togglingIds = this.togglingIds.filter((x) => x !== id);

                if (!data) { row.is_active = !next; return; }

                this._applyServerResponse(data);
                if (data.message) {
                    this.$store.toasts.push({ type: 'success', message: data.message });
                }
            },

            /** Bind this workstation to a terminal (server sets the cookie). */
            async selectTerminal(id) {
                if (this.selectingId) return;
                const row = this.rowsById[id];
                if (!row || row.is_active === false) return;

                this.selectingId = id;
                const data = await this._send(selectUrlTemplate.replace('__ID__', id), this._tokenForm());
                this.selectingId = null;
                if (!data) return;

                this.activeTerminalId = data.selected_id ?? id;
                if (data.message) {
                    this.$store.toasts.push({ type: 'success', message: data.message });
                }
            },

            /** Unbind this workstation from any terminal (clears the cookie). */
            async clearSelection() {
                const data = await this._send(clearSelectionUrl, this._tokenForm());
                if (!data) return;

                this.activeTerminalId = null;
                if (data.message) {
                    this.$store.toasts.push({ type: 'success', message: data.message });
                }
            },

            confirmDelete() {
                this.confirmDeleteRow(this.form.id);
            },

            confirmDeleteRow(id) {
                const name = this.rowsById[id]?.name ?? 'this terminal';
                this.$store.confirm.show({
                    title:        `Delete "${name}"?`,
                    message:      'Past sales and shifts keep their history but lose the terminal label. This cannot be undone.',
                    intent:       'danger',
                    confirmLabel: 'Delete terminal',
                    cancelLabel:  'Cancel',
                    onConfirm: async () => {
                        const data = await this._send(deleteUrlTemplate.replace('__ID__', id), this._formWithMethod('DELETE'));
                        if (!data) return;
                        this._applyServerResponse(data);
                        if (this.form.id === id) this.closeEditor();
                        if (data.message) {
                            this.$store.toasts.push({ type: 'success', message: data.message });
                        }
                    },
                });
            },

            async submitEditor(evt) {
                if (this.submitting) return;
                this.submitting = true;

                const data = await this._send(this.formAction, new FormData(evt.target), evt.target);
                if (!data) { this.submitting = false; return; }

                this._applyServerResponse(data);
                if (data.message) {
                    this.$store.toasts.push({ type: 'success', message: data.message });
                }
                if (data.id) this.openEdit(data.id);
                this.submitting = false;
            },

            _applyServerResponse(data) {
                if (Array.isArray(data.rows)) {
                    this.rowsById = Object.fromEntries(data.rows.map((r) => [r.id, r]));
                }
                if (data.list_html) {
                    const list = this._rootEl.querySelector('.term-list');
                    if (list) {
                        list.replaceChildren();
                        list.insertAdjacentHTML('beforeend', data.list_html);
                        if (window.Alpine) window.Alpine.initTree(list);
                    }
                }
                this._dtCollect();
                this._dtRender();
                this.$nextTick(() => { this._dtCollect(); this._dtRender(); });
            },

            async _send(url, body, formEl = null) {
                try {
                    const { data } = await posPost(url, body);
                    return data;
                } catch (e) {
                    if (e?.status === 422) {
                        const errs = e.errors ?? {};
                        const messages = Object.values(errs).flat().filter(Boolean);
                        if (messages.length) {
                            this.$store.toasts.push({
                                type:    'error',
                                title:   messages.length === 1 ? 'Please review the form' : 'Please fix the errors below',
                                messages,
                            });
                        } else {
                            this.$store.toasts.push({ type: 'error', message: e?.message || 'Request failed.' });
                        }
                        if (formEl) applyValidationErrors(formEl, errs);
                    }
                    return null;
                }
            },

            _formWithMethod(method) {
                const fd = new FormData();
                fd.append('_token',  document.querySelector('meta[name="csrf-token"]')?.content || '');
                fd.append('_method', method);
                return fd;
            },

            _tokenForm() {
                const fd = new FormData();
                fd.append('_token', document.querySelector('meta[name="csrf-token"]')?.content || '');
                return fd;
            },
        },
    );
}
