/**
 * ServiceSupplierWorkspace — پورتال تأمین‌کننده (کاتالوگ + سفارشات)
 */
const TYPE_LABELS = { part: 'قطعه', service: 'خدمات', equipment: 'تجهیزات' };
const STATUS_LABELS = {
    supplier_pending: 'در انتظار تأمین‌کننده',
    pending: 'در انتظار',
    quoted: 'پیش‌فاکتور شده',
    ready: 'آماده ارسال',
    shipped: 'ارسال شده',
    delivered: 'تحویل شده',
    cancelled: 'لغو',
};

export default class ServiceSupplierWorkspace {
    constructor({ root, request, profile, siteUrl }) {
        this.root = root;
        this.request = request;
        this.profile = profile || {};
        this.siteUrl = siteUrl || '/acc-engine/';
        this._tab = 'catalog';
        this._catalog = [];
        this._orders = [];
        this._openOrders = [];
        this._types = TYPE_LABELS;
        this._editingId = 0;
        this._filterType = '';
        this._searchQ = '';
    }

    esc(t) {
        return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    _fmt(n) {
        return Number(n || 0).toLocaleString('fa-IR');
    }

    _toast(msg, isErr = false) {
        let el = this.root.querySelector('.svc-toast');
        if (!el) {
            el = document.createElement('div');
            el.className = 'svc-toast';
            this.root.appendChild(el);
        }
        el.textContent = msg;
        el.className = 'svc-toast' + (isErr ? ' svc-toast--err' : ' svc-toast--ok');
        el.style.display = 'block';
        clearTimeout(this._toastT);
        this._toastT = setTimeout(() => { el.style.display = 'none'; }, 3500);
    }

    async init() {
        await this._loadMe();
        this.root.innerHTML = this._shellHtml();
        this._bindEvents();
        await this._loadTabData();
        this._renderTab();
    }

    async _loadMe() {
        try {
            const res = await this.request('GET', 'service/supplier/me');
            const d = res?.data ?? res;
            this.profile = d?.profile ?? this.profile;
            this._stats = d?.catalog_stats ?? {};
            this._orderStats = d?.order_stats ?? {};
            this._types = d?.item_types ?? TYPE_LABELS;
        } catch {
            this._stats = {};
            this._orderStats = {};
        }
    }

    _shellHtml() {
        const p = this.profile || {};
        const cs = this._stats || {};
        const os = this._orderStats || {};
        return `<div class="svc-sup-ws" dir="rtl">
            <div class="svc-ws-hero svc-sup-hero">
                <div class="svc-ws-hero__main">
                    <span class="svc-ws-hero__icon">📦</span>
                    <div>
                        <div class="svc-ws-hero__name">${this.esc(p.company_name || 'تأمین‌کننده')}</div>
                        <div class="svc-ws-hero__sub">${this.esc(p.city || '')} · کاتالوگ فعال: ${cs.active ?? 0} از ${cs.total ?? 0}</div>
                    </div>
                </div>
            </div>
            <div class="svc-ws-kpis svc-sup-kpis">
                <div class="svc-ws-kpi"><span class="svc-ws-kpi__n">${cs.parts ?? 0}</span><span class="svc-ws-kpi__l">قطعات</span></div>
                <div class="svc-ws-kpi"><span class="svc-ws-kpi__n">${cs.services ?? 0}</span><span class="svc-ws-kpi__l">خدمات</span></div>
                <div class="svc-ws-kpi"><span class="svc-ws-kpi__n">${os.open ?? 0}</span><span class="svc-ws-kpi__l">سفارش باز</span></div>
                <div class="svc-ws-kpi"><span class="svc-ws-kpi__n">${os.quoted ?? 0}</span><span class="svc-ws-kpi__l">پیش‌فاکتور</span></div>
            </div>
            <div class="svc-ws-tabs svc-sup-tabs" data-ref="tabs">
                <button class="svc-ws-tab ${this._tab === 'catalog' ? 'svc-ws-tab--active' : ''}" data-tab="catalog">📋 کاتالوگ من</button>
                <button class="svc-ws-tab ${this._tab === 'open' ? 'svc-ws-tab--active' : ''}" data-tab="open">🔔 سفارشات باز</button>
                <button class="svc-ws-tab ${this._tab === 'orders' ? 'svc-ws-tab--active' : ''}" data-tab="orders">📦 سفارشات من</button>
                <button class="svc-ws-tab ${this._tab === 'profile' ? 'svc-ws-tab--active' : ''}" data-tab="profile">🏢 پروفایل</button>
            </div>
            <div class="svc-ws-panel" data-ref="panel"></div>
        </div>`;
    }

    _bindEvents() {
        this.root.querySelector('[data-ref="tabs"]')?.querySelectorAll('[data-tab]').forEach(btn => {
            btn.addEventListener('click', async () => {
                const tab = btn.dataset.tab;
                if (tab === this._tab) return;
                this._tab = tab;
                this.root.querySelectorAll('[data-ref="tabs"] .svc-ws-tab').forEach(b =>
                    b.classList.toggle('svc-ws-tab--active', b.dataset.tab === tab));
                await this._loadTabData();
                this._renderTab();
            });
        });
    }

    async _loadTabData() {
        if (this._tab === 'catalog') {
            const q = this._searchQ ? `?q=${encodeURIComponent(this._searchQ)}` : '';
            const type = this._filterType ? `${q ? '&' : '?'}type=${this._filterType}` : '';
            const res = await this.request('GET', `service/supplier/catalog${q}${type}`);
            this._catalog = res?.data ?? [];
        } else if (this._tab === 'open') {
            const res = await this.request('GET', 'service/supplier/orders/open');
            this._openOrders = res?.data ?? [];
        } else if (this._tab === 'orders') {
            const res = await this.request('GET', 'service/supplier/orders');
            this._orders = res?.data ?? [];
        }
    }

    _renderTab() {
        const panel = this.root.querySelector('[data-ref="panel"]');
        if (!panel) return;
        if (this._tab === 'catalog') panel.innerHTML = this._catalogHtml();
        else if (this._tab === 'open') panel.innerHTML = this._openOrdersHtml();
        else if (this._tab === 'orders') panel.innerHTML = this._ordersHtml();
        else panel.innerHTML = this._profileHtml();
        this._bindPanelEvents();
    }

    _catalogHtml() {
        const rows = this._catalog.map(item => `
            <tr data-id="${item.id}">
                <td><span class="svc-sup-type svc-sup-type--${item.item_type}">${this.esc(item.item_type_label || TYPE_LABELS[item.item_type])}</span></td>
                <td><strong>${this.esc(item.name)}</strong><div class="svc-sup-sku">${this.esc(item.sku)}</div></td>
                <td>${this.esc(item.brand)} ${item.model ? '· ' + this.esc(item.model) : ''}</td>
                <td>${this._fmt(item.price)}</td>
                <td>${item.in_stock ? item.stock_qty : '—'}</td>
                <td>${item.is_active ? '✅' : '⏸'}</td>
                <td class="svc-sup-actions">
                    <button class="svc-btn svc-btn--sm" data-act="edit" data-id="${item.id}">ویرایش</button>
                    <button class="svc-btn svc-btn--sm svc-btn--danger" data-act="del" data-id="${item.id}">حذف</button>
                </td>
            </tr>`).join('');

        return `<div class="svc-sup-toolbar">
            <input type="search" class="svc-input" placeholder="جستجو..." data-ref="searchQ" value="${this.esc(this._searchQ)}">
            <select class="svc-input" data-ref="filterType">
                <option value="">همه انواع</option>
                ${Object.entries(this._types).map(([k, v]) =>
                    `<option value="${k}" ${this._filterType === k ? 'selected' : ''}>${this.esc(v)}</option>`).join('')}
            </select>
            <button class="svc-btn svc-btn--primary" data-act="add">+ افزودن کالا/خدمت</button>
        </div>
        ${this._catalog.length ? `<div class="svc-sup-table-wrap"><table class="svc-sup-table">
            <thead><tr><th>نوع</th><th>نام / SKU</th><th>برند</th><th>قیمت (ریال)</th><th>موجودی</th><th>فعال</th><th></th></tr></thead>
            <tbody>${rows}</tbody>
        </table></div>` : '<div class="acc-empty">کاتالوگ خالی است — اولین کالا را اضافه کنید.</div>'}
        <div class="svc-sup-form-overlay" data-ref="formOverlay" style="display:none"></div>`;
    }

    _itemFormHtml(item = {}) {
        const types = this._types;
        return `<div class="svc-sup-form">
            <h3>${item.id ? 'ویرایش آیتم' : 'افزودن به کاتالوگ'}</h3>
            <form data-ref="itemForm">
                <div class="svc-sup-form-grid">
                    <label>نوع<select name="item_type" required>
                        ${Object.entries(types).map(([k, v]) =>
                            `<option value="${k}" ${(item.item_type || 'part') === k ? 'selected' : ''}>${this.esc(v)}</option>`).join('')}
                    </select></label>
                    <label>نام *<input name="name" required value="${this.esc(item.name)}"></label>
                    <label>کد SKU<input name="sku" value="${this.esc(item.sku)}"></label>
                    <label>برند<input name="brand" value="${this.esc(item.brand)}"></label>
                    <label>مدل<input name="model" value="${this.esc(item.model)}"></label>
                    <label>قیمت (ریال)<input name="price" type="number" min="0" value="${item.price ?? 0}"></label>
                    <label>موجودی<input name="stock_qty" type="number" min="0" value="${item.stock_qty ?? 0}"></label>
                    <label>زمان تأمین (روز)<input name="lead_days" type="number" min="0" value="${item.lead_days ?? 3}"></label>
                    <label class="svc-sup-check"><input type="checkbox" name="in_stock" ${item.in_stock !== false ? 'checked' : ''}> موجود</label>
                    <label class="svc-sup-check"><input type="checkbox" name="is_active" ${item.is_active !== false ? 'checked' : ''}> فعال</label>
                </div>
                <label>توضیحات<textarea name="description" rows="2">${this.esc(item.description)}</textarea></label>
                <div class="svc-sup-form-actions">
                    <button type="submit" class="svc-btn svc-btn--primary">ذخیره</button>
                    <button type="button" class="svc-btn" data-act="cancel-form">انصراف</button>
                </div>
            </form>
        </div>`;
    }

    _openOrdersHtml() {
        if (!this._openOrders.length) {
            return '<div class="acc-empty">سفارش بازی مطابق کاتالوگ شما نیست.</div>';
        }
        return `<div class="svc-sup-cards">${this._openOrders.map(o => `
            <div class="svc-sup-order-card">
                <div class="svc-sup-order-head">
                    <strong>${this.esc(o.part_number)}</strong>
                    <span class="svc-sup-badge">${this.esc(STATUS_LABELS[o.status] || o.status)}</span>
                </div>
                <div class="svc-sup-order-meta">تعداد: ${o.part_qty} · مشتری: ${this.esc(o.customer_name || '—')}</div>
                <div class="svc-sup-order-actions">
                    <input type="number" class="svc-input svc-input--sm" placeholder="قیمت پیشنهادی" data-ref="quote-${o.id}">
                    <button class="svc-btn svc-btn--primary svc-btn--sm" data-act="claim" data-id="${o.id}">پذیرش و پیش‌فاکتور</button>
                </div>
            </div>`).join('')}</div>`;
    }

    _ordersHtml() {
        if (!this._orders.length) {
            return '<div class="acc-empty">هنوز سفارشی به شما تخصیص نشده.</div>';
        }
        return `<div class="svc-sup-cards">${this._orders.map(o => `
            <div class="svc-sup-order-card">
                <div class="svc-sup-order-head">
                    <strong>#${o.id} — ${this.esc(o.part_number)}</strong>
                    <span class="svc-sup-badge">${this.esc(STATUS_LABELS[o.status] || o.status)}</span>
                </div>
                <div class="svc-sup-order-meta">
                    تعداد: ${o.part_qty} · قیمت: ${this._fmt(o.quote_price)} ریال · ETA: ${o.eta_days} روز
                </div>
                ${o.status === 'quoted' ? `
                <div class="svc-sup-order-actions">
                    <button class="svc-btn svc-btn--sm" data-act="ship" data-id="${o.id}">ارسال شد</button>
                    <button class="svc-btn svc-btn--sm svc-btn--primary" data-act="deliver" data-id="${o.id}">تحویل شد</button>
                </div>` : ''}
            </div>`).join('')}</div>`;
    }

    _profileHtml() {
        const p = this.profile || {};
        return `<form class="svc-sup-profile-form" data-ref="profileForm">
            <div class="svc-sup-form-grid">
                <label>نام شرکت<input name="company_name" value="${this.esc(p.company_name)}"></label>
                <label>نام تماس<input name="contact_name" value="${this.esc(p.contact_name)}"></label>
                <label>تلفن<input name="phone" value="${this.esc(p.phone)}"></label>
                <label>ایمیل<input name="email" value="${this.esc(p.email)}"></label>
                <label>شهر<input name="city" value="${this.esc(p.city)}"></label>
            </div>
            <label>آدرس<input name="address" value="${this.esc(p.address)}"></label>
            <label>توضیحات<textarea name="description" rows="3">${this.esc(p.description)}</textarea></label>
            <button type="submit" class="svc-btn svc-btn--primary">ذخیره پروفایل</button>
        </form>`;
    }

    _bindPanelEvents() {
        const panel = this.root.querySelector('[data-ref="panel"]');
        if (!panel) return;

        panel.querySelector('[data-act="add"]')?.addEventListener('click', () => {
            this._editingId = 0;
            this._showForm();
        });

        panel.querySelectorAll('[data-act="edit"]').forEach(btn => {
            btn.addEventListener('click', () => {
                const id = Number(btn.dataset.id);
                const item = this._catalog.find(c => c.id === id);
                this._editingId = id;
                this._showForm(item);
            });
        });

        panel.querySelectorAll('[data-act="del"]').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('حذف این آیتم از کاتالوگ؟')) return;
                try {
                    await this.request('DELETE', `service/supplier/catalog/${btn.dataset.id}`);
                    this._toast('حذف شد');
                    await this._loadMe();
                    await this._loadTabData();
                    this._renderTab();
                } catch (e) {
                    this._toast(e.message || 'خطا', true);
                }
            });
        });

        panel.querySelector('[data-ref="searchQ"]')?.addEventListener('change', async (e) => {
            this._searchQ = e.target.value.trim();
            await this._loadTabData();
            this._renderTab();
        });

        panel.querySelector('[data-ref="filterType"]')?.addEventListener('change', async (e) => {
            this._filterType = e.target.value;
            await this._loadTabData();
            this._renderTab();
        });

        panel.querySelectorAll('[data-act="claim"]').forEach(btn => {
            btn.addEventListener('click', async () => {
                const id = btn.dataset.id;
                const priceEl = panel.querySelector(`[data-ref="quote-${id}"]`);
                const price = priceEl ? Number(priceEl.value) : 0;
                try {
                    await this.request('POST', `service/supplier/orders/${id}/claim`, {
                        quote_price: price || undefined,
                    });
                    this._toast('سفارش پذیرفته شد');
                    await this._loadMe();
                    await this._loadTabData();
                    this._renderTab();
                } catch (e) {
                    this._toast(e.message || 'خطا', true);
                }
            });
        });

        panel.querySelectorAll('[data-act="ship"], [data-act="deliver"]').forEach(btn => {
            btn.addEventListener('click', async () => {
                const status = btn.dataset.act === 'ship' ? 'shipped' : 'delivered';
                try {
                    await this.request('PUT', `service/supplier/orders/${btn.dataset.id}`, { status });
                    this._toast('وضعیت به‌روز شد');
                    await this._loadMe();
                    await this._loadTabData();
                    this._renderTab();
                } catch (e) {
                    this._toast(e.message || 'خطا', true);
                }
            });
        });

        panel.querySelector('[data-ref="profileForm"]')?.addEventListener('submit', async (e) => {
            e.preventDefault();
            const fd = new FormData(e.target);
            const body = Object.fromEntries(fd.entries());
            try {
                const res = await this.request('PUT', 'service/supplier/profile', body);
                this.profile = res?.data ?? body;
                this._toast('پروفایل ذخیره شد');
            } catch (err) {
                this._toast(err.message || 'خطا', true);
            }
        });
    }

    _showForm(item = {}) {
        const overlay = this.root.querySelector('[data-ref="formOverlay"]')
            || this.root.querySelector('[data-ref="panel"]')?.querySelector('[data-ref="formOverlay"]');
        if (!overlay) return;
        overlay.style.display = 'flex';
        overlay.innerHTML = this._itemFormHtml(item);

        overlay.querySelector('[data-act="cancel-form"]')?.addEventListener('click', () => {
            overlay.style.display = 'none';
        });

        overlay.querySelector('[data-ref="itemForm"]')?.addEventListener('submit', async (e) => {
            e.preventDefault();
            const fd = new FormData(e.target);
            const body = {
                item_type: fd.get('item_type'),
                name: fd.get('name'),
                sku: fd.get('sku'),
                brand: fd.get('brand'),
                model: fd.get('model'),
                price: Number(fd.get('price') || 0),
                stock_qty: Number(fd.get('stock_qty') || 0),
                lead_days: Number(fd.get('lead_days') || 0),
                description: fd.get('description'),
                in_stock: fd.get('in_stock') === 'on',
                is_active: fd.get('is_active') === 'on',
            };
            try {
                if (this._editingId) {
                    await this.request('PUT', `service/supplier/catalog/${this._editingId}`, body);
                } else {
                    await this.request('POST', 'service/supplier/catalog', body);
                }
                overlay.style.display = 'none';
                this._toast('ذخیره شد');
                await this._loadMe();
                await this._loadTabData();
                this._renderTab();
            } catch (err) {
                this._toast(err.message || 'خطا', true);
            }
        });
    }

    destroy() {
        clearTimeout(this._toastT);
    }
}
