/**
 * ProjectsCPMSection.js — مدیریت پروژه‌ها (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

const STATUS_LABELS = {
    planned:   { label: "برنامه‌ریزی",  color: "#6366f1", bg: "#eef2ff" },
    active:    { label: "فعال",          color: "#059669", bg: "#ecfdf5" },
    on_hold:   { label: "متوقف",         color: "#d97706", bg: "#fffbeb" },
    completed: { label: "تکمیل‌شده",     color: "#0284c7", bg: "#e0f2fe" },
    cancelled: { label: "لغو‌شده",       color: "#dc2626", bg: "#fef2f2" },
};

const TYPE_LABELS = {
    construction:  "ساختمانی",
    software:      "نرم‌افزاری",
    infrastructure:"زیرساخت",
    other:         "سایر",
};

export default class ProjectsCPMSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this.cpmView  = props.cpmView ?? null;
        this._projects = [];
        this._lands    = [];
        this._search   = "";
    }

    async template() {
        return `
            <div class="cpm-section-wrap">
                <div class="cpm-toolbar">
                    <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">+ پروژه جدید</button>
                    <input type="text" data-ref="searchIn" placeholder="جستجو نام / کد..."
                           style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;min-width:200px;">
                    <select data-ref="statusFilter" style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;">
                        <option value="">همه وضعیت‌ها</option>
                        <option value="planned">برنامه‌ریزی</option>
                        <option value="active">فعال</option>
                        <option value="on_hold">متوقف</option>
                        <option value="completed">تکمیل‌شده</option>
                        <option value="cancelled">لغو‌شده</option>
                    </select>
                </div>
                <div class="cpm-grid" data-ref="grid"></div>
            </div>
        `;
    }

    async afterRender() {
        // Pre-load lands for the form
        try {
            const r = await this.api.get("/pc/lands");
            this._lands = r?.data ?? [];
        } catch { /* non-fatal */ }

        this.on(this.ref("addBtn"),      "click", () => this._openForm(null));
        this.on(this.ref("searchIn"),    "input", () => this._debouncedLoad());
        this.on(this.ref("statusFilter"),"change",() => this._load());
        await this._load();
    }

    _debouncedLoad() {
        clearTimeout(this._searchTimer);
        this._searchTimer = setTimeout(() => this._load(), 280);
    }

    async _load() {
        const grid = this.ref("grid");
        grid.innerHTML = `<div class="cpm-loading"><div class="acc-spinner"></div></div>`;
        const params = {};
        const s = this.ref("searchIn")?.value?.trim();
        const st = this.ref("statusFilter")?.value;
        if (s)  params.search = s;
        if (st) params.status = st;
        try {
            const res = await this.api.get("/pc/projects", params);
            this._projects = res?.data ?? [];
            this._render(grid);
        } catch {
            grid.innerHTML = `<div class="acc-empty">خطا در بارگذاری پروژه‌ها</div>`;
        }
    }

    _render(grid) {
        if (!this._projects.length) {
            grid.innerHTML = `<div class="acc-empty" style="grid-column:1/-1">پروژه‌ای یافت نشد.</div>`;
            return;
        }
        grid.innerHTML = "";
        this._projects.forEach(p => {
            const st  = STATUS_LABELS[p.status] ?? { label: p.status, color: "#64748b", bg: "#f1f5f9" };
            const pct = parseFloat(p.progress ?? 0).toFixed(0);
            const card = document.createElement("div");
            card.className = "cpm-project-card";
            card.innerHTML = `
                <div class="cpm-project-card__head">
                    <span class="cpm-project-card__code">${this.escape(p.code || "#" + p.id)}</span>
                    <span class="cpm-status-badge" style="background:${st.bg};color:${st.color}">${st.label}</span>
                </div>
                <div class="cpm-project-card__name">${this.escape(p.name)}</div>
                <div class="cpm-project-card__meta">
                    <span>🏗 ${TYPE_LABELS[p.type] ?? p.type}</span>
                    ${p.start_date ? `<span>📅 ${p.start_date}</span>` : ""}
                    ${p.manager_name ? `<span>👤 ${this.escape(p.manager_name)}</span>` : ""}
                </div>
                <div class="cpm-progress-bar-wrap">
                    <div class="cpm-progress-bar" style="width:${pct}%"></div>
                    <span class="cpm-progress-label">${pct}٪</span>
                </div>
                ${p.budget > 0 ? `<div class="cpm-project-card__budget">💰 بودجه: ${Number(p.budget).toLocaleString('fa-IR')} ریال</div>` : ""}
                <div class="cpm-project-card__actions">
                    <button class="acc-btn acc-btn--primary acc-btn--sm" data-action="select">🎯 انتخاب</button>
                    <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="edit">ویرایش</button>
                    <button class="acc-btn acc-btn--sm" data-action="loc" style="background:#dbeafe;color:#1e40af;">📍 محل پروژه</button>
                    <button class="acc-btn acc-btn--danger acc-btn--sm" data-action="del">حذف</button>
                </div>
            `;
            card.querySelector("[data-action='select']").addEventListener("click", () => {
                if (this.cpmView) this.cpmView.selectProject(p);
                this._highlightSelected(card);
            });
            card.querySelector("[data-action='edit']").addEventListener("click",   () => this._openForm(p));
            card.querySelector("[data-action='del']").addEventListener("click",    () => this._delete(p));
            card.querySelector("[data-action='loc']").addEventListener("click",    () => LocationPicker.openModal({
                api: this.api, entityType: 'project', entityId: p.id, entityName: p.name || `پروژه #${p.id}`,
            }));
            grid.appendChild(card);
        });
    }

    _highlightSelected(activeCard) {
        this.ref("grid")?.querySelectorAll(".cpm-project-card").forEach(c =>
            c.classList.toggle("cpm-project-card--selected", c === activeCard)
        );
    }

    // ── Respond to project change from outside (e.g. badge close) ──
    onProjectChange(project) {
        if (!project) {
            this.ref("grid")?.querySelectorAll(".cpm-project-card").forEach(c =>
                c.classList.remove("cpm-project-card--selected")
            );
        }
    }

    /* ── Form modal ─────────────────────────────────────────────── */

    _openForm(p = null) {
        const isEdit = !!p;
        const landOpts = this._lands.map(l =>
            `<option value="${l.id}" ${p?.land_id == l.id ? "selected" : ""}>${this.escape(l.name)}</option>`
        ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:600px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${isEdit ? "ویرایش پروژه" : "پروژه جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>کد پروژه</label>
                            <input name="code" value="${this.escape(p?.code || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>نام پروژه *</label>
                            <input name="name" value="${this.escape(p?.name || "")}" required>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نوع پروژه</label>
                            <select name="type">
                                <option value="construction" ${p?.type==="construction"?"selected":""}>ساختمانی</option>
                                <option value="software"     ${p?.type==="software"?"selected":""}>نرم‌افزاری</option>
                                <option value="infrastructure" ${p?.type==="infrastructure"?"selected":""}>زیرساخت</option>
                                <option value="other"        ${p?.type==="other"?"selected":""}>سایر</option>
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>وضعیت</label>
                            <select name="status">
                                <option value="planned"   ${p?.status==="planned"?"selected":""}>برنامه‌ریزی</option>
                                <option value="active"    ${p?.status==="active"?"selected":""}>فعال</option>
                                <option value="on_hold"   ${p?.status==="on_hold"?"selected":""}>متوقف</option>
                                <option value="completed" ${p?.status==="completed"?"selected":""}>تکمیل‌شده</option>
                                <option value="cancelled" ${p?.status==="cancelled"?"selected":""}>لغو‌شده</option>
                            </select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>تاریخ شروع</label>
                            <input type="date" name="start_date" value="${this.escape(p?.start_date || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>تاریخ پایان</label>
                            <input type="date" name="end_date" value="${this.escape(p?.end_date || "")}">
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>بودجه (ریال)</label>
                            <input type="number" name="budget" value="${this.escape(p?.budget || "0")}" min="0">
                        </div>
                        <div class="acc-form-group">
                            <label>زمین</label>
                            <select name="land_id">
                                <option value="">— بدون زمین —</option>
                                ${landOpts}
                            </select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نام مدیر پروژه</label>
                            <input name="manager_name" value="${this.escape(p?.manager_name || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>ارز</label>
                            <select name="currency">
                                <option value="IRR" ${p?.currency==="IRR"?"selected":""}>ریال (IRR)</option>
                                <option value="USD" ${p?.currency==="USD"?"selected":""}>دلار (USD)</option>
                            </select>
                        </div>
                    </div>
                    <div class="acc-form-group">
                        <label>توضیحات</label>
                        <textarea name="description" rows="3">${this.escape(p?.description || "")}</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">${isEdit ? "ذخیره" : "ایجاد پروژه"}</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", ev => { if (ev.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            if (!body.land_id) delete body.land_id;
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/pc/projects/${p.id}`, body);
                else        await this.api.post("/pc/projects", body);
                close(); await this._load();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "ایجاد پروژه";
            }
        });
    }

    async _delete(p) {
        if (!confirm(`حذف پروژه «${p.name}»؟ تمام وظایف و داده‌های مرتبط نیز حذف می‌شوند.`)) return;
        try {
            await this.api.delete(`/pc/projects/${p.id}`);
            await this._load();
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }
}
