/**
 * PurchaseInvoicesSection.js
 * فاکتور خرید — لیست + فرم ردیف‌دار + نهایی‌سازی خودکار حسابداری
 */

import SectionBase from "../../accounting/SectionBase.js";
import CreateShipmentDialog from "../../shipping/components/CreateShipmentDialog.js";

export default class PurchaseInvoicesSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this._view         = "list";
        this._editInvoice  = null;
        this._suppliers    = [];
        this._products     = [];
        this._projects     = [];
        this._warehouses   = [];
        this._invoices     = [];
        this._totals       = {};
        this._page         = 1;
        this._statusFilter = "";
    }

    async template() {
        return `<div data-ref="root"></div>`;
    }

    async afterRender() {
        await this._loadLookups();
        await this._showList();
    }

    /* ─── Lookups ─────────────────────────────────────────────── */

    async _loadLookups() {
        try {
            const [sRes, pRes, prjRes, wRes] = await Promise.all([
                this.api.get("/purchase/suppliers"),
                this.api.get("/sales/products"),
                this.api.get("/pc/projects", { per_page: 200 }).catch(() => null),
                this.api.get("/inv/warehouses").catch(() => ({ data: [] })),
            ]);
            this._suppliers  = sRes?.data  ?? [];
            this._products   = pRes?.data  ?? [];
            this._projects   = prjRes?.data ?? [];
            this._warehouses = wRes?.data  ?? [];
        } catch { /* non-fatal */ }
    }

    /* ══════════════════════════════════════════════════════════════
       LIST VIEW
    ══════════════════════════════════════════════════════════════ */

    async _showList() {
        this._view = "list";
        const root = this.ref("root");
        root.innerHTML = `
            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px;flex-wrap:wrap;">
                <button class="acc-btn acc-btn--primary" data-ref="newBtn">➕ فاکتور خرید جدید</button>
                <select class="event-type-filter" data-ref="statusSel" style="min-width:140px;">
                    <option value="">همه وضعیت‌ها</option>
                    <option value="draft">پیش‌نویس</option>
                    <option value="finalized">نهایی‌شده</option>
                    <option value="cancelled">لغوشده</option>
                </select>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄</button>
                <span style="margin-right:auto;font-size:12px;color:#94a3b8;" data-ref="countLbl"></span>
            </div>
            <div data-ref="listBody"></div>
            <div data-ref="pagination" style="display:flex;gap:8px;margin-top:14px;justify-content:center;"></div>
        `;

        this._bindRef();

        this.on(this.ref("newBtn"),    "click",  () => this._showForm(null));
        this.on(this.ref("refreshBtn"),"click",  () => this._loadList());
        this.on(this.ref("statusSel"), "change", e => {
            this._statusFilter = e.target.value;
            this._page = 1;
            this._loadList();
        });

        await this._loadList();
    }

    _bindRef() {
        const root = this.ref("root");
        if (!root) return;
        root.querySelectorAll("[data-ref]").forEach(el => {
            this.refs[el.dataset.ref] = el;
        });
    }

    async _loadList() {
        const body = this.ref("listBody");
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;

        try {
            const params = { page: this._page, per_page: 20 };
            if (this._statusFilter) params.status = this._statusFilter;
            const res = await this.api.get("/purchase/invoices", params);
            this._invoices = res?.data ?? [];
            const total    = res?.total ?? this._invoices.length;

            this.ref("countLbl").textContent = `${total} فاکتور خرید`;
            this._renderList(body);
            this._renderPagination(total, 20);
        } catch {
            body.innerHTML = `<div class="acc-error">خطا در دریافت فاکتورها</div>`;
        }
    }

    _renderList(body) {
        if (!this._invoices.length) {
            body.innerHTML = `<div class="acc-empty">فاکتور خریدی یافت نشد.</div>`;
            return;
        }
        body.innerHTML = "";
        this._invoices.forEach(inv => {
            const card = this._buildCard(inv);
            body.appendChild(card);
        });
    }

    _buildCard(inv) {
        const statusClass = { draft:"draft", finalized:"finalized", cancelled:"cancelled" }[inv.status] ?? "draft";
        const statusLabel = { draft:"پیش‌نویس", finalized:"نهایی‌شده", cancelled:"لغوشده" }[inv.status] ?? inv.status;

        const div = document.createElement("div");
        // purchase card gets a purple left-border accent via inline override
        div.className = `invoice-card invoice-card--${statusClass}`;
        div.style.borderRight = inv.status === "finalized" ? "4px solid #7c3aed" : "";

        div.innerHTML = `
            <div style="flex:1;min-width:0;">
                <div class="invoice-card__no">${this.escape(inv.invoice_no)}</div>
                <div class="invoice-card__party">${this.escape(inv.supplier_name || "—")}</div>
                <div class="invoice-card__date">
                    📅 ${inv.invoice_date}
                    <span class="status-badge status-badge--${statusClass === "finalized" ? "confirmed" : statusClass === "cancelled" ? "cancelled" : "draft"}"
                          style="margin-right:8px;">${statusLabel}</span>
                    ${inv.acc_event_id ? `<span class="acc-link-badge">🔗 رویداد #${inv.acc_event_id}</span>` : ""}
                </div>
                ${inv.ref_number ? `<div style="font-size:11px;color:#94a3b8;margin-top:2px;">شماره فاکتور تأمین‌کننده: ${this.escape(inv.ref_number)}</div>` : ""}
                ${inv.project_name ? `<div style="font-size:11px;color:#4f46e5;margin-top:2px;">🏗 پروژه: ${this.escape(inv.project_name)}</div>` : ""}
            </div>
            <div style="text-align:left;">
                <div class="invoice-card__amount">${this._fmt(inv.total_amount)} ﷼</div>
                <div class="invoice-card__actions" style="margin-top:8px;">
                    ${inv.status === "draft" ? `
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="edit">ویرایش</button>
                        <button class="acc-btn acc-btn--primary   acc-btn--sm" data-action="finalize">✅ نهایی‌سازی</button>
                        <button class="acc-btn acc-btn--danger    acc-btn--sm" data-action="delete">حذف</button>
                    ` : ""}
                    ${inv.status === "finalized" ? `
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="view">مشاهده</button>
                        <button class="acc-btn acc-btn--sm" data-action="ship" style="background:#dbeafe;color:#1e40af;">🚚 ایجاد محموله</button>
                    ` : ""}
                </div>
            </div>
        `;

        div.querySelector("[data-action='edit']")?.addEventListener("click",     e => { e.stopPropagation(); this._showForm(inv); });
        div.querySelector("[data-action='finalize']")?.addEventListener("click", e => { e.stopPropagation(); this._finalize(inv.id); });
        div.querySelector("[data-action='delete']")?.addEventListener("click",   e => { e.stopPropagation(); this._delete(inv.id); });
        div.querySelector("[data-action='view']")?.addEventListener("click",     e => { e.stopPropagation(); this._showForm(inv, true); });
        div.querySelector("[data-action='ship']")?.addEventListener("click",     async e => {
            e.stopPropagation();
            const res = await this.api.get(`/purchase/invoices/${inv.id}`);
            CreateShipmentDialog.open({
                api: this.api,
                source: 'purchase',
                invoiceId: inv.id,
                invoiceItems: res?.data?.items ?? [],
            });
        });

        return div;
    }

    _renderPagination(total, size) {
        const pg    = this.ref("pagination");
        const pages = Math.ceil(total / size);
        if (!pg || pages <= 1) { if (pg) pg.innerHTML = ""; return; }
        pg.innerHTML = "";
        for (let i = 1; i <= pages; i++) {
            const b = document.createElement("button");
            b.className = `acc-btn acc-btn--sm ${i === this._page ? "acc-btn--primary" : "acc-btn--secondary"}`;
            b.textContent = i;
            b.addEventListener("click", () => { this._page = i; this._loadList(); });
            pg.appendChild(b);
        }
    }

    /* ══════════════════════════════════════════════════════════════
       FORM VIEW
    ══════════════════════════════════════════════════════════════ */

    async _showForm(invoice = null, readOnly = false) {
        this._view        = "form";
        this._editInvoice = invoice;

        const root = this.ref("root");

        const suppOpts = `<option value="">— انتخاب تأمین‌کننده —</option>` +
            this._suppliers.map(s => `<option value="${s.id}">${this.escape(s.name)}</option>`).join("");

        const whOpts = `<option value="">— انتخاب انبار ورود —</option>` +
            this._warehouses.map(w => `<option value="${w.id}">${this.escape(w.name)}</option>`).join("");

        root.innerHTML = `
            <div class="inv-page">
                <!-- Header -->
                <div class="inv-header inv-header--purchase">
                    <div class="acc-form-group" style="margin:0">
                        <label>تأمین‌کننده</label>
                        <select data-ref="fSupplier" ${readOnly?"disabled":""}>
                            ${suppOpts}
                        </select>
                    </div>
                    <div class="acc-form-group" style="margin:0">
                        <label>🏭 انبار ورود کالا</label>
                        <select data-ref="fWarehouse" ${readOnly?"disabled":""}>
                            ${whOpts}
                        </select>
                    </div>
                    <div class="acc-form-group" style="margin:0">
                        <label>تاریخ فاکتور</label>
                        <input type="date" data-ref="fDate" value="${invoice?.invoice_date || this._today()}" ${readOnly?"readonly":""}>
                    </div>
                    <div class="acc-form-group" style="margin:0">
                        <label>تاریخ سررسید</label>
                        <input type="date" data-ref="fDue" value="${invoice?.due_date || ""}" ${readOnly?"readonly":""}>
                    </div>
                    <div class="acc-form-group" style="margin:0">
                        <label>شماره فاکتور تأمین‌کننده</label>
                        <input type="text" data-ref="fRef" value="${this.escape(invoice?.ref_number||"")}" ${readOnly?"readonly":""} placeholder="اختیاری">
                    </div>
                    <div class="acc-form-group" style="margin:0">
                        <label>سررسید پرداخت (روز)</label>
                        <input type="number" data-ref="fPayTerm" value="${invoice?.payment_terms||30}" min="0" ${readOnly?"readonly":""}>
                    </div>
                    <div class="acc-form-group" style="margin:0;grid-column:1/-1;">
                        <label>شرح کلی</label>
                        <input type="text" data-ref="fDesc" value="${this.escape(invoice?.description||"")}" ${readOnly?"readonly":""}>
                    </div>
                    ${this._projects.length ? `
                    <div class="acc-form-group" style="margin:0;">
                        <label>پروژه (اختیاری)</label>
                        <select data-ref="fProject" ${readOnly?"disabled":""}>
                            <option value="">— بدون پروژه —</option>
                            ${this._projects.map(p => `<option value="${p.id}" ${invoice?.project_id == p.id ? "selected" : ""}>${this.escape(p.name)}</option>`).join("")}
                        </select>
                    </div>` : ""}
                </div>

                <!-- Items -->
                <div class="inv-items-wrapper">
                    <div class="inv-items-title">
                        📋 ردیف‌های فاکتور خرید
                        ${!readOnly ? `<button type="button" class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="addItemBtn">+ ردیف</button>` : ""}
                    </div>
                    <table class="inv-items-table">
                        <thead>
                            <tr>
                                <th style="width:28px">#</th>
                                <th style="min-width:160px">محصول/خدمت</th>
                                <th style="min-width:130px">شرح</th>
                                <th style="width:70px">تعداد</th>
                                <th style="width:110px">قیمت خرید</th>
                                <th style="width:60px">تخفیف%</th>
                                <th style="width:60px">مالیات%</th>
                                <th style="width:110px">جمع ردیف</th>
                                ${!readOnly ? "<th style='width:30px'></th>" : ""}
                            </tr>
                        </thead>
                        <tbody data-ref="itemsBody"></tbody>
                    </table>
                </div>

                <!-- Totals -->
                <div class="inv-totals">
                    <table class="inv-totals-table">
                        <tr><td>جمع کل قبل از تخفیف</td><td data-ref="tSubtotal">0</td></tr>
                        <tr><td>تخفیف</td><td data-ref="tDiscount" style="color:#dc2626;">0</td></tr>
                        <tr><td>مبلغ خالص</td><td data-ref="tNet">0</td></tr>
                        <tr><td>مالیات ارزش افزوده</td><td data-ref="tVat">0</td></tr>
                        <tr class="inv-total-main"><td>مبلغ قابل پرداخت</td>
                            <td data-ref="tTotal" style="color:#7c3aed !important;">0</td>
                        </tr>
                    </table>
                </div>

                <!-- Actions -->
                ${!readOnly ? `
                <div class="inv-actions">
                    <button class="acc-btn acc-btn--secondary" data-ref="backBtn">← بازگشت</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="saveDraftBtn">💾 ذخیره پیش‌نویس</button>
                    <button class="acc-btn acc-btn--primary"   data-ref="finalizeBtn"
                            style="background:#7c3aed;border-color:#7c3aed;">
                        ✅ نهایی‌سازی + ثبت حسابداری
                    </button>
                    <span data-ref="formSpinner" style="display:none;" class="acc-loading">
                        <span class="acc-spinner"></span>
                    </span>
                </div>
                ` : `
                <div class="inv-actions">
                    <button class="acc-btn acc-btn--secondary" data-ref="backBtn">← بازگشت</button>
                </div>
                `}
            </div>
        `;

        this._bindRef();

        this.on(this.ref("backBtn"), "click", () => this._showList());

        if (!readOnly) {
            this.on(this.ref("addItemBtn"),   "click", () => this._addItemRow());
            this.on(this.ref("saveDraftBtn"), "click", () => this._saveInvoice("draft"));
            this.on(this.ref("finalizeBtn"),  "click", () => this._saveAndFinalize());
        }

        // Prefill fields
        if (invoice?.supplier_id)  this.ref("fSupplier").value  = invoice.supplier_id;
        if (invoice?.warehouse_id) this.ref("fWarehouse").value = invoice.warehouse_id;

        // Load existing items
        if (invoice?.id) {
            try {
                const res = await this.api.get(`/purchase/invoices/${invoice.id}`);
                const existing = res?.data?.items ?? [];
                existing.forEach(it => this._addItemRow(it));
            } catch { /* add empty row */ }
        }

        if (!this.ref("itemsBody").querySelectorAll("tr").length && !readOnly) this._addItemRow();
        this._updateTotals();
    }

    /* ── Item row ───────────────────────────────────────────────── */

    _addItemRow(item = {}) {
        const body    = this.ref("itemsBody");
        const idx     = body.querySelectorAll("tr").length;
        const prodOpts = `<option value="">— انتخاب —</option>` +
            this._products.map(p => `<option value="${p.id}" data-price="${p.cost_price||p.sale_price||0}" data-vat="${p.vat_rate||0}">${this.escape(p.name)}</option>`).join("");

        const tr = document.createElement("tr");
        tr.innerHTML = `
            <td style="text-align:center;color:#94a3b8;font-size:12px;" class="row-num">${idx + 1}</td>
            <td><select class="item-product">${prodOpts}</select></td>
            <td><input class="item-desc" type="text" value="${this.escape(item.description||"")}" placeholder="شرح ردیف"></td>
            <td><input class="item-qty" type="number" value="${item.quantity||1}" min="0.001" step="any"></td>
            <td><input class="item-price" type="number" value="${item.unit_price||0}" min="0" step="any"></td>
            <td><input class="item-disc" type="number" value="${item.discount_pct||0}" min="0" max="100" step="0.1"></td>
            <td><input class="item-vat" type="number" value="${item.vat_rate||9}" min="0" max="100" step="0.1"></td>
            <td class="inv-line-total">0</td>
            <td><button type="button" class="acc-btn acc-btn--danger acc-btn--sm" style="padding:3px 8px;">×</button></td>
        `;

        // Pre-select product
        if (item.product_id) tr.querySelector(".item-product").value = item.product_id;

        // Product change → auto-fill cost_price & VAT
        tr.querySelector(".item-product").addEventListener("change", e => {
            const opt = e.target.selectedOptions[0];
            if (opt?.dataset.price) tr.querySelector(".item-price").value = opt.dataset.price;
            if (opt?.dataset.vat)   tr.querySelector(".item-vat").value   = opt.dataset.vat;
            if (!tr.querySelector(".item-desc").value && opt?.textContent) {
                tr.querySelector(".item-desc").value = opt.textContent.trim();
            }
            this._calcRow(tr);
            this._updateTotals();
        });

        // Recalculate on any input change
        tr.querySelectorAll("input").forEach(el => {
            el.addEventListener("input", () => { this._calcRow(tr); this._updateTotals(); });
        });

        // Remove row
        tr.querySelector("button").addEventListener("click", () => {
            tr.remove();
            this._renumberRows();
            this._updateTotals();
        });

        body.appendChild(tr);
        this._calcRow(tr);
        this._updateTotals();
    }

    _calcRow(tr) {
        const qty   = parseFloat(tr.querySelector(".item-qty")?.value)   || 0;
        const price = parseFloat(tr.querySelector(".item-price")?.value) || 0;
        const disc  = parseFloat(tr.querySelector(".item-disc")?.value)  || 0;
        const vat   = parseFloat(tr.querySelector(".item-vat")?.value)   || 0;
        const base  = qty * price;
        const dAmt  = base * (disc / 100);
        const net   = base - dAmt;
        const vatAmt= net * (vat / 100);
        const total = net + vatAmt;
        tr.querySelector(".inv-line-total").textContent = this._fmt(total);
        return { base, dAmt, net, vatAmt, total };
    }

    _renumberRows() {
        this.ref("itemsBody")?.querySelectorAll("tr").forEach((tr, i) => {
            const n = tr.querySelector(".row-num");
            if (n) n.textContent = i + 1;
        });
    }

    _updateTotals() {
        let subtotal = 0, disc = 0, net = 0, vat = 0;
        this.ref("itemsBody")?.querySelectorAll("tr").forEach(tr => {
            const c = this._calcRow(tr);
            subtotal += c.base; disc += c.dAmt; net += c.net; vat += c.vatAmt;
        });
        this._totals = { subtotal, discount_amount: disc, net_amount: net, vat_amount: vat, total_amount: net + vat };
        this._setRef("tSubtotal", this._fmt(subtotal));
        this._setRef("tDiscount", this._fmt(disc));
        this._setRef("tNet",      this._fmt(net));
        this._setRef("tVat",      this._fmt(vat));
        this._setRef("tTotal",    this._fmt(net + vat));
    }

    _setRef(name, val) { const el = this.ref(name); if (el) el.textContent = val; }

    /* ── Collect items ──────────────────────────────────────────── */

    _collectItems() {
        const rows = [];
        this.ref("itemsBody")?.querySelectorAll("tr").forEach(tr => {
            rows.push({
                product_id:   tr.querySelector(".item-product")?.value || null,
                description:  tr.querySelector(".item-desc")?.value    || "",
                quantity:     parseFloat(tr.querySelector(".item-qty")?.value)   || 0,
                unit_price:   parseFloat(tr.querySelector(".item-price")?.value) || 0,
                discount_pct: parseFloat(tr.querySelector(".item-disc")?.value)  || 0,
                vat_rate:     parseFloat(tr.querySelector(".item-vat")?.value)   || 9,
            });
        });
        return rows.filter(r => r.quantity > 0);
    }

    _buildPayload() {
        const projectVal = this.ref("fProject")?.value;
        return {
            supplier_id:    this.ref("fSupplier")?.value  || null,
            warehouse_id:   this.ref("fWarehouse")?.value || null,
            invoice_date:   this.ref("fDate")?.value      || this._today(),
            due_date:       this.ref("fDue")?.value       || null,
            ref_number:     this.ref("fRef")?.value      || "",
            payment_terms:  parseInt(this.ref("fPayTerm")?.value ?? 30),
            description:    this.ref("fDesc")?.value     || "",
            project_id:     projectVal ? parseInt(projectVal) : null,
            items:          this._collectItems(),
        };
    }

    /* ── Save draft ─────────────────────────────────────────────── */

    async _saveInvoice(status = "draft") {
        const items = this._collectItems();
        if (!items.length) { alert("حداقل یک ردیف وارد کنید."); return null; }

        const body = this._buildPayload();
        this._setFormBusy(true);
        try {
            let res;
            if (this._editInvoice?.id) {
                res = await this.api.put(`/purchase/invoices/${this._editInvoice.id}`, body);
                return this._editInvoice.id;
            } else {
                res = await this.api.post("/purchase/invoices", body);
                this._editInvoice = { id: res?.id };
                return res?.id;
            }
        } catch (err) {
            alert("خطا: " + (err?.message ?? ""));
            return null;
        } finally {
            this._setFormBusy(false);
        }
    }

    /* ── Save + Finalize ────────────────────────────────────────── */

    async _saveAndFinalize() {
        const id = await this._saveInvoice("draft");
        if (!id) return;
        await this._finalize(id);
    }

    async _finalize(invoiceId) {
        this._setFormBusy(true);
        try {
            const res = await this.api.post(`/purchase/invoices/${invoiceId}/finalize`, {});
            if (res?.success) {
                this._toast(`✅ فاکتور خرید نهایی شد — رویداد حسابداری #${res.event_id} ثبت گردید`);
                await this._showList();
            } else {
                alert("خطا: " + (res?.message ?? ""));
            }
        } catch (err) {
            alert("خطا: " + (err?.message ?? ""));
        } finally {
            this._setFormBusy(false);
        }
    }

    async _delete(id) {
        if (!confirm("حذف این فاکتور خرید؟")) return;
        try {
            await this.api.delete(`/purchase/invoices/${id}`);
            await this._loadList();
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    /* ── Helpers ────────────────────────────────────────────────── */

    _setFormBusy(busy) {
        const spn = this.ref("formSpinner");
        const sb  = this.ref("saveDraftBtn");
        const fb  = this.ref("finalizeBtn");
        if (spn) spn.style.display = busy ? "flex" : "none";
        if (sb)  sb.disabled  = busy;
        if (fb)  fb.disabled  = busy;
    }

    _today() { return new Date().toISOString().slice(0, 10); }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Math.round(Number(v ?? 0))); }

    _toast(msg) {
        const t = document.createElement("div");
        t.style.cssText = "position:fixed;bottom:24px;right:24px;background:#7c3aed;color:#fff;padding:13px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;box-shadow:0 4px 20px rgba(0,0,0,.15);max-width:360px;";
        t.textContent = msg;
        document.body.appendChild(t);
        setTimeout(() => t.remove(), 4000);
    }
}
