/**
 * MembersSection.js — اعضای تیم پروژه
 */
import SectionBase from "../../accounting/SectionBase.js";

const ROLE_LABELS = {
    manager:    { label: "مدیر پروژه",    icon: "👑", color: "#7c3aed", bg: "#f5f3ff" },
    engineer:   { label: "مهندس",          icon: "🔧", color: "#2563eb", bg: "#eff6ff" },
    supervisor: { label: "ناظر",           icon: "👁",  color: "#0891b2", bg: "#ecfeff" },
    worker:     { label: "کارگر",          icon: "🦺", color: "#d97706", bg: "#fffbeb" },
    consultant: { label: "مشاور",          icon: "💼", color: "#059669", bg: "#ecfdf5" },
    client:     { label: "کارفرما",        icon: "🏢", color: "#dc2626", bg: "#fef2f2" },
    other:      { label: "سایر",           icon: "👤", color: "#6b7280", bg: "#f3f4f6" },
};

export default class MembersSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this.cpmView    = props.cpmView ?? null;
        this._projectId = null;
        this._members   = [];
    }

    async template() {
        return `
            <div class="cpm-section-wrap">
                <div class="cpm-section-notice" data-ref="notice">
                    <span>⚠️ لطفاً ابتدا یک پروژه از تب «پروژه‌ها» انتخاب کنید.</span>
                </div>
                <div data-ref="content" style="display:none">
                    <div class="cpm-toolbar">
                        <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">+ عضو جدید</button>
                        <select data-ref="roleFilter" style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;">
                            <option value="">همه نقش‌ها</option>
                            <option value="manager">مدیر پروژه</option>
                            <option value="engineer">مهندس</option>
                            <option value="supervisor">ناظر</option>
                            <option value="worker">کارگر</option>
                            <option value="consultant">مشاور</option>
                            <option value="client">کارفرما</option>
                            <option value="other">سایر</option>
                        </select>
                        <input type="text" data-ref="searchIn" placeholder="جستجو نام..."
                               style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;min-width:180px;">
                    </div>
                    <div class="cpm-grid" data-ref="grid"></div>
                </div>
            </div>
        `;
    }

    async afterRender() {
        // notice shown by default
    }

    async onProjectChange(project) {
        this._projectId = project?.id ?? null;
        if (!this._projectId) {
            this.ref("notice").style.display = "flex";
            this.ref("content").style.display = "none";
            return;
        }
        this.ref("notice").style.display = "none";
        this.ref("content").style.display = "block";

        this.on(this.ref("addBtn"),     "click",  () => this._openForm(null));
        this.on(this.ref("roleFilter"), "change", () => this._render());
        this.on(this.ref("searchIn"),   "input",  () => this._render());

        await this._load();
    }

    async _load() {
        const grid = this.ref("grid");
        grid.innerHTML = `<div class="cpm-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get(`/pc/projects/${this._projectId}/members`);
            this._members = res?.data ?? [];
            this._render();
        } catch {
            grid.innerHTML = `<div class="acc-empty">خطا در بارگذاری اعضا</div>`;
        }
    }

    _render() {
        const grid   = this.ref("grid");
        const role   = this.ref("roleFilter")?.value;
        const search = this.ref("searchIn")?.value?.trim().toLowerCase();

        let members = this._members;
        if (role)   members = members.filter(m => m.role === role);
        if (search) members = members.filter(m =>
            m.name?.toLowerCase().includes(search) ||
            m.email?.toLowerCase().includes(search)
        );

        if (!members.length) {
            grid.innerHTML = `<div class="acc-empty" style="grid-column:1/-1">عضوی یافت نشد.</div>`;
            return;
        }

        grid.innerHTML = "";
        members.forEach(m => {
            const rl = ROLE_LABELS[m.role] ?? ROLE_LABELS.other;
            const card = document.createElement("div");
            card.className = "cpm-member-card" + (!m.is_active ? " cpm-member-card--inactive" : "");
            card.innerHTML = `
                <div class="cpm-member-card__avatar" style="background:${rl.bg};color:${rl.color}">
                    ${rl.icon}
                </div>
                <div class="cpm-member-card__info">
                    <div class="cpm-member-card__name">${this.escape(m.name)}</div>
                    <div class="cpm-member-card__role">
                        <span class="cpm-badge" style="background:${rl.bg};color:${rl.color}">${rl.label}</span>
                        ${!m.is_active ? `<span class="cpm-badge" style="background:#fee2e2;color:#dc2626">غیرفعال</span>` : ""}
                    </div>
                    <div class="cpm-member-card__meta">
                        ${m.email ? `📧 ${this.escape(m.email)}` : ""}
                        ${m.phone ? ` | 📱 ${this.escape(m.phone)}` : ""}
                        ${m.joined_at ? `<br>📅 پیوستن: ${m.joined_at}` : ""}
                    </div>
                </div>
                <div class="cpm-member-card__actions">
                    <button class="acc-btn acc-btn--secondary acc-btn--xs" data-action="edit">ویرایش</button>
                    <button class="acc-btn ${m.is_active ? "acc-btn--warning" : "acc-btn--success"} acc-btn--xs" data-action="toggle">
                        ${m.is_active ? "غیرفعال" : "فعال‌سازی"}
                    </button>
                    <button class="acc-btn acc-btn--danger acc-btn--xs" data-action="del">حذف</button>
                </div>
            `;
            card.querySelector("[data-action='edit']").addEventListener("click",   () => this._openForm(m));
            card.querySelector("[data-action='toggle']").addEventListener("click", () => this._toggleActive(m));
            card.querySelector("[data-action='del']").addEventListener("click",    () => this._delete(m));
            grid.appendChild(card);
        });
    }

    _openForm(m = null) {
        const isEdit = !!m;
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:520px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${isEdit ? "ویرایش عضو" : "عضو جدید"}</div>
                <form>
                    <div class="acc-form-group">
                        <label>نام و نام خانوادگی *</label>
                        <input name="name" value="${this.escape(m?.name || "")}" required>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>ایمیل</label>
                            <input type="email" name="email" value="${this.escape(m?.email || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>تلفن</label>
                            <input name="phone" value="${this.escape(m?.phone || "")}">
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نقش *</label>
                            <select name="role">
                                <option value="manager"    ${m?.role==="manager"?"selected":""}>مدیر پروژه</option>
                                <option value="engineer"   ${m?.role==="engineer"?"selected":""}>مهندس</option>
                                <option value="supervisor" ${m?.role==="supervisor"?"selected":""}>ناظر</option>
                                <option value="worker"     ${m?.role==="worker"?"selected":""}>کارگر</option>
                                <option value="consultant" ${m?.role==="consultant"?"selected":""}>مشاور</option>
                                <option value="client"     ${m?.role==="client"?"selected":""}>کارفرما</option>
                                <option value="other"      ${m?.role==="other"?"selected":""}>سایر</option>
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>تاریخ پیوستن</label>
                            <input type="date" name="joined_at" value="${this.escape(m?.joined_at || "")}">
                        </div>
                    </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());
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/pc/members/${m.id}`, body);
                else        await this.api.post(`/pc/projects/${this._projectId}/members`, body);
                close(); await this._load();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "افزودن";
            }
        });
    }

    async _toggleActive(m) {
        try {
            await this.api.put(`/pc/members/${m.id}`, { is_active: m.is_active ? 0 : 1 });
            await this._load();
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    async _delete(m) {
        if (!confirm(`حذف عضو «${m.name}»؟`)) return;
        try { await this.api.delete(`/pc/members/${m.id}`); await this._load(); }
        catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }
}
