/**
 * ShipmentsSection.js — لیست محموله‌ها + tracking
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_COLORS = {
    pending:'#94a3b8', ordered:'#6366f1', preparing:'#3b82f6', packed:'#06b6d4',
    picked_up:'#8b5cf6', in_transit:'#f59e0b', out_for_delivery:'#f97316',
    arrived:'#10b981', inspection:'#eab308', received:'#059669',
    delivered:'#059669', rejected:'#ef4444', failed:'#ef4444',
    returned:'#dc2626', cancelled:'#64748b',
};

const STATUS_LABELS = {
    pending:'در انتظار', ordered:'سفارش شده', preparing:'آماده‌سازی', packed:'بسته‌بندی شده',
    picked_up:'تحویل به حمل', in_transit:'در حال حمل', out_for_delivery:'ارسال نهایی',
    arrived:'رسید', inspection:'بازرسی', received:'پذیرفته شد',
    delivered:'تحویل مشتری', rejected:'رد شد', failed:'ناموفق',
    returned:'مرجوعی', cancelled:'لغو شد',
};

export default class ShipmentsSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🚚 محموله‌ها</h2>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <select data-ref="dirFilter" class="acc-input">
                        <option value="">همه جهت‌ها</option>
                        <option value="inbound">📥 ورودی (خرید)</option>
                        <option value="outbound">📤 خروجی (فروش)</option>
                        <option value="transfer">🔄 انتقالی</option>
                    </select>
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS_LABELS).map(([k,v]) => `<option value="${k}">${v}</option>`).join("")}
                    </select>
                    <input type="text" data-ref="search" placeholder="🔍 شماره/کد رهگیری/گیرنده" class="acc-input" style="width:220px;">
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._load();
        this.on(this.ref("refreshBtn"),   "click",  () => this._load());
        this.on(this.ref("dirFilter"),    "change", () => this._load());
        this.on(this.ref("statusFilter"), "change", () => this._load());
        this.on(this.ref("search"),       "input",  () => { clearTimeout(this._t); this._t = setTimeout(() => this._load(), 300); });
    }

    async _load() {
        const params = {};
        const dir = this.ref("dirFilter")?.value;
        const st  = this.ref("statusFilter")?.value;
        const q   = this.ref("search")?.value?.trim();
        if (dir) params.direction = dir;
        if (st)  params.status    = st;
        if (q)   params.search    = q;

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/ship/shipments", params);
            this._rows = res?.data ?? [];
            this._render();
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render() {
        if (!this._rows.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">محموله‌ای یافت نشد</div>`;
            return;
        }
        this.ref("wrap").innerHTML = `
        <table class="acc-table">
            <thead><tr>
                <th>شماره</th><th>جهت</th><th>روش حمل</th><th>وضعیت</th>
                <th>مرجع</th><th>گیرنده</th><th>زمان</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${this._rows.map(s => {
                const color = STATUS_COLORS[s.status] ?? '#64748b';
                const label = STATUS_LABELS[s.status] ?? s.status;
                const dirIcon = s.direction === 'outbound' ? '📤' : (s.direction === 'transfer' ? '🔄' : '📥');
                const delayed = s.planned_delivery_date &&
                    new Date(s.planned_delivery_date) < new Date() &&
                    !s.actual_delivery_date &&
                    !['received','delivered','cancelled','rejected'].includes(s.status);
                return `<tr ${delayed ? 'style="background:#fef2f2;"' : ''}>
                    <td>
                        <b style="font-family:monospace;">${this.escape(s.shipment_no)}</b>
                        ${delayed ? '<br><small style="color:#ef4444;">⏰ تأخیر</small>' : ''}
                    </td>
                    <td>${dirIcon}</td>
                    <td>${s.method_icon || '🚚'} <small>${this.escape(s.method_name ?? '—')}</small></td>
                    <td><span style="background:${color}1a;color:${color};padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${label}</span></td>
                    <td><small>${this.escape(s.ref_no ?? '—')}</small></td>
                    <td><small>${this.escape(s.recipient_name ?? '—')}</small></td>
                    <td><small>${s.planned_delivery_date ?? '—'}</small></td>
                    <td><button class="acc-btn acc-btn--xs acc-btn--primary" data-view="${s.id}">📦 مشاهده</button></td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-view]").forEach(b =>
            b.addEventListener("click", () => this._viewShipment(parseInt(b.dataset.view)))
        );
    }

    async _viewShipment(id) {
        try {
            const res = await this.api.get(`/ship/shipments/${id}`);
            const s = res?.data;
            if (!s) return;
            this._renderShipmentModal(s);
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    _renderShipmentModal(s) {
        const color = STATUS_COLORS[s.status] ?? '#64748b';
        const label = STATUS_LABELS[s.status] ?? s.status;
        const dirIcon = s.direction === 'outbound' ? '📤 خروجی' : '📥 ورودی';

        // مراحل بعدی برای حرکت
        const nextStages = this._getNextStages(s.direction, s.status);

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:780px;max-height:92vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${s.method_icon ?? '🚚'} محموله ${this.escape(s.shipment_no)}</div>

            <!-- وضعیت -->
            <div style="background:${color}1a;border-right:4px solid ${color};padding:10px 14px;border-radius:6px;margin-bottom:14px;">
                <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
                    <div>
                        <span style="color:${color};font-weight:700;font-size:16px;">${label}</span>
                        <div style="font-size:11px;color:#64748b;margin-top:2px;">${dirIcon} | ${this.escape(s.method_name ?? '')}</div>
                    </div>
                    <div style="display:flex;gap:6px;flex-wrap:wrap;">
                        ${nextStages.map(n => `
                        <button class="acc-btn acc-btn--xs" data-advance="${n}" style="background:${STATUS_COLORS[n]}1a;color:${STATUS_COLORS[n]};border:1px solid ${STATUS_COLORS[n]}55;">
                            ⏭️ ${STATUS_LABELS[n]}
                        </button>
                        `).join("")}
                        ${s.direction === 'inbound' && ['arrived','inspection'].includes(s.status) ? `
                        <button class="acc-btn acc-btn--xs" data-action="inspect" style="background:#fef9c3;color:#854d0e;">🔍 ثبت بازرسی</button>` : ''}
                    </div>
                </div>
            </div>

            <!-- مشخصات -->
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px;font-size:12px;">
                ${s.ref_no ? `<div><b>مرجع:</b> ${this.escape(s.ref_no)}</div>` : ''}
                ${s.warehouse_name ? `<div><b>انبار مقصد:</b> ${this.escape(s.warehouse_name)}</div>` : ''}
                ${s.from_warehouse_name ? `<div><b>انبار مبدأ:</b> ${this.escape(s.from_warehouse_name)}</div>` : ''}
                ${s.carrier_full_name ? `<div><b>شرکت حمل:</b> ${this.escape(s.carrier_full_name)}</div>` : ''}
                ${s.driver_name ? `<div><b>راننده:</b> ${this.escape(s.driver_name)}</div>` : ''}
                ${s.vehicle_plate ? `<div><b>پلاک:</b> <span dir="ltr">${this.escape(s.vehicle_plate)}</span></div>` : ''}
                ${s.tracking_code ? `<div><b>کد رهگیری:</b> <span dir="ltr">${this.escape(s.tracking_code)}</span></div>` : ''}
                ${s.recipient_name ? `<div><b>گیرنده:</b> ${this.escape(s.recipient_name)} ${s.recipient_phone ? '— '+this.escape(s.recipient_phone) : ''}</div>` : ''}
                ${s.planned_delivery_date ? `<div><b>برنامه تحویل:</b> ${s.planned_delivery_date}</div>` : ''}
                ${s.actual_delivery_date ? `<div style="color:#10b981;"><b>زمان واقعی تحویل:</b> ${s.actual_delivery_date}</div>` : ''}
            </div>

            <!-- آیتم‌ها -->
            <div style="margin-bottom:14px;">
                <h4 style="margin:0 0 8px 0;font-size:13px;color:#475569;">📦 آیتم‌های محموله</h4>
                <table class="acc-table" style="font-size:12px;">
                    <thead><tr><th>محصول</th><th>تعداد برنامه</th><th>تحویل</th><th>دریافت</th><th>خسارت</th></tr></thead>
                    <tbody>
                    ${(s.items ?? []).map(i => `<tr>
                        <td>${this.escape(i.product_name)}</td>
                        <td>${this._fmt(i.qty_planned)} ${this.escape(i.unit ?? '')}</td>
                        <td>${this._fmt(i.qty_shipped)}</td>
                        <td>${this._fmt(i.qty_received)}</td>
                        <td style="color:${parseFloat(i.qty_damaged) > 0 ? '#ef4444' : 'inherit'};">${this._fmt(i.qty_damaged)}</td>
                    </tr>`).join("")}
                    </tbody>
                </table>
            </div>

            <!-- Timeline -->
            <div style="margin-bottom:14px;">
                <h4 style="margin:0 0 8px 0;font-size:13px;color:#475569;">⏱️ Timeline مراحل</h4>
                <div style="border-right:2px solid #e2e8f0;padding-right:14px;">
                    ${(s.stages ?? []).reverse().map(st => `
                    <div style="position:relative;padding:6px 0;">
                        <div style="position:absolute;right:-20px;top:10px;width:10px;height:10px;background:#3b82f6;border-radius:50%;border:2px solid #fff;box-shadow:0 0 0 1px #3b82f6;"></div>
                        <div style="font-size:12px;font-weight:600;color:#1e293b;">${this.escape(st.title)}</div>
                        <div style="font-size:11px;color:#94a3b8;">${st.created_at} ${st.actor_name ? '— '+this.escape(st.actor_name) : ''}</div>
                        ${st.notes ? `<div style="font-size:11px;color:#64748b;margin-top:2px;">${this.escape(st.notes)}</div>` : ''}
                    </div>`).join("") || '<div style="color:#94a3b8;font-size:12px;">مرحله‌ای ثبت نشده</div>'}
                </div>
            </div>

            <!-- بازرسی‌ها -->
            ${(s.inspections ?? []).length ? `
            <div style="margin-bottom:14px;">
                <h4 style="margin:0 0 8px 0;font-size:13px;color:#475569;">🔍 بازرسی‌ها</h4>
                ${s.inspections.map(i => `
                <div style="background:#fef9c3;border-right:3px solid #eab308;padding:8px 12px;border-radius:6px;margin-bottom:6px;font-size:12px;">
                    <b>امتیاز: ${i.quality_score}/100</b> — ${i.result}
                    ${i.damage_report ? '<br>'+this.escape(i.damage_report) : ''}
                    <div style="font-size:10px;color:#94a3b8;margin-top:3px;">👤 ${this.escape(i.inspector_name)} — ${i.inspection_date}</div>
                </div>
                `).join("")}
            </div>` : ''}

            <div class="acc-modal__actions">
                <button class="acc-btn acc-btn--secondary" data-action="close">بستن</button>
            </div>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=close]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });

        // advance buttons
        ov.querySelectorAll("[data-advance]").forEach(btn =>
            btn.addEventListener("click", async () => {
                const newStatus = btn.dataset.advance;
                const notes = prompt(`یادداشت برای انتقال به «${STATUS_LABELS[newStatus]}»:`, '');
                if (notes === null) return;
                try {
                    await this.api.post(`/ship/shipments/${s.id}/advance`, { status: newStatus, notes });
                    this._toast(`✅ منتقل شد به: ${STATUS_LABELS[newStatus]}`);
                    close(); this._load();
                } catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );

        // inspect
        const inspBtn = ov.querySelector("[data-action=inspect]");
        if (inspBtn) inspBtn.addEventListener("click", () => { close(); this._openInspectModal(s.id); });
    }

    _openInspectModal(shipmentId) {
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🔍 ثبت بازرسی محموله</div>
            <form>
                <div class="acc-form-group"><label>امتیاز کیفی (0-100)</label>
                    <input name="quality_score" type="number" min="0" max="100" value="80" required>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin:10px 0;">
                    <label style="display:flex;gap:4px;align-items:center;font-size:12px;">
                        <input type="checkbox" name="packaging_ok" value="1" checked> ✅ بسته‌بندی
                    </label>
                    <label style="display:flex;gap:4px;align-items:center;font-size:12px;">
                        <input type="checkbox" name="quantity_ok" value="1" checked> ✅ تعداد
                    </label>
                    <label style="display:flex;gap:4px;align-items:center;font-size:12px;">
                        <input type="checkbox" name="specs_ok" value="1" checked> ✅ مشخصات
                    </label>
                </div>
                <div class="acc-form-group"><label>نتیجه نهایی</label>
                    <select name="result">
                        <option value="accepted">✅ پذیرفته شد</option>
                        <option value="partial">🟡 پذیرش جزئی</option>
                        <option value="rejected">❌ رد شد</option>
                    </select>
                </div>
                <div class="acc-form-group"><label>گزارش خسارت</label>
                    <textarea name="damage_report" rows="2"></textarea>
                </div>
                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">ثبت بازرسی</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            body.packaging_ok = body.packaging_ok ? 1 : 0;
            body.quantity_ok  = body.quantity_ok ? 1 : 0;
            body.specs_ok     = body.specs_ok ? 1 : 0;
            try {
                await this.api.post(`/ship/shipments/${shipmentId}/inspect`, body);
                close(); this._toast("✅ بازرسی ثبت شد"); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    /** مراحل بعدی مجاز برای هر وضعیت */
    _getNextStages(direction, current) {
        const inboundOrder  = ['pending','ordered','preparing','picked_up','in_transit','arrived','inspection','received'];
        const outboundOrder = ['pending','preparing','packed','picked_up','in_transit','out_for_delivery','delivered'];
        const order = direction === 'outbound' ? outboundOrder : inboundOrder;
        const idx = order.indexOf(current);
        if (idx < 0 || idx === order.length - 1) return [];
        const next = [order[idx + 1]];
        // امکان لغو همیشه
        if (direction === 'inbound')  next.push('cancelled', 'rejected');
        if (direction === 'outbound') next.push('failed', 'returned', 'cancelled');
        return next;
    }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Number(v ?? 0)); }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    _toast(m, b = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${b};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;z-index:9999;`;
        t.textContent = m; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
