import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import { Cpm } from "../../../../cpm-project/src/cpm.js";

class CpmProjectView extends BaseView {

    static title = "کنترل پروژه (CPM)";

    useContextBadge = true;

    STATUS_META = {
        planned: {
            label: "برنامه‌ریزی",
            color: "#64748b",
            bg: "#f1f5f9"
        },
        active: {
            label: "فعال",
            color: "#2563eb",
            bg: "#dbeafe"
        },
        on_hold: {
            label: "متوقف",
            color: "#f59e0b",
            bg: "#fef3c7"
        },
        completed: {
            label: "تکمیل",
            color: "#10b981",
            bg: "#d1fae5"
        },
        cancelled: {
            label: "لغو شده",
            color: "#ef4444",
            bg: "#fee2e2"
        }
    };

    async render(container) {

        await super.render(container);

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

        body.innerHTML = `
            <div class="cpm-wrapper">

                <h2 class="cpm-page-title">
                    📊 کنترل پروژه (CPM)
                </h2>

                <div
                    id="cpm-project-board"
                    class="cpm-board">
                </div>

            </div>
        `;

        await this.loadProjects();

        return this;
    }

    async loadProjects() {

        const board = this.ref("body")
            .querySelector("#cpm-project-board");

        board.innerHTML = `
            <div class="cpm-loading">
                در حال بارگذاری پروژه‌ها...
            </div>
        `;

        try {

            const res = await fetch("/wp-json/cpm/v1/projects", {
                method: "GET",
                credentials: "include",
                headers: {
                    "Content-Type": "application/json"
                }
            });

            if (!res.ok) {
                throw new Error(`HTTP ${res.status}`);
            }

            const projects = await res.json();

            this.renderCards(projects);

        } catch (error) {

            console.error(
                "CPM loadProjects error:",
                error
            );

            board.innerHTML = `
                <div class="cpm-error">
                    خطا در دریافت پروژه‌ها
                </div>
            `;
        }
    }

    renderCards(projects = []) {

        const board = this.ref("body")
            .querySelector("#cpm-project-board");

        board.innerHTML = "";

        if (!projects.length) {

            board.innerHTML = `
                <div class="cpm-empty">
                    پروژه‌ای یافت نشد
                </div>
            `;

            return;
        }

        Object.entries(this.STATUS_META)
            .forEach(([statusKey, meta]) => {

                const statusProjects = projects.filter(
                    p => (p.status || "planned") === statusKey
                );

                if (!statusProjects.length) {
                    return;
                }

                const column = document.createElement("div");

                column.className = "cpm-column";

                column.innerHTML = `

                    <div class="cpm-column-header">

                        <div class="cpm-column-title">

                            <span
                                class="cpm-column-dot"
                                style="background:${meta.color}">
                            </span>

                            <span>${meta.label}</span>

                        </div>

                        <div class="cpm-column-count">
                            ${statusProjects.length}
                        </div>

                    </div>

                    <div class="cpm-column-cards"></div>

                `;

                const cardsContainer =
                    column.querySelector(".cpm-column-cards");

                statusProjects.forEach(project => {

                    const card =
                        this.createProjectCard(project);

                    cardsContainer.appendChild(card);

                });

                board.appendChild(column);

            });
    }

    createProjectCard(project) {

        const meta =
            this.STATUS_META[project.status] ||
            this.STATUS_META.planned;

        const progress =
            Math.round(project.progress || 0);

        const card = document.createElement("div");

        card.className = "cpm-card";

        card.innerHTML = `

            <div class="cpm-card-header">

                <div>

                    <div class="cpm-card-title">
                        ${project.name || "-"}
                    </div>

                    <div class="cpm-card-code">
                        ${project.code || ""}
                    </div>

                </div>

                <div
                    class="cpm-card-status"
                    style="
                        background:${meta.bg};
                        color:${meta.color};
                    "
                >

                    <span
                        class="cpm-status-dot"
                        style="background:${meta.color}">
                    </span>

                    ${meta.label}

                </div>

            </div>

            <div class="cpm-stats-grid">

                ${this.createStat("📅 تقویم‌ها", project.calendars)}
                ${this.createStat("🗓 روزهای کاری", project.calendar_days)}
                ${this.createStat("🧱 WBS", project.wbs)}
                ${this.createStat("✅ فعالیت‌ها", project.tasks)}
                ${this.createStat("🔗 وابستگی‌ها", project.dependencies)}
                ${this.createStat("👷 منابع", project.resources)}
                ${this.createStat("📌 تخصیص‌ها", project.assignments)}
                ${this.createStat("💰 آیتم مالی", project.financial_items)}
                ${this.createStat("💵 هزینه فعالیت", project.task_costs)}
                ${this.createStat("🏦 هزینه پروژه", project.project_costs)}
                ${this.createStat("📈 Cashflow", project.cashflow)}

            </div>

            <div class="cpm-progress-wrapper">

                <div class="cpm-progress-text">

                    <span>پیشرفت پروژه</span>

                    <strong>${progress}%</strong>

                </div>

                <div class="cpm-progress">

                    <div
                        class="cpm-progress-fill"
                        style="width:${progress}%">
                    </div>

                </div>

            </div>

        `;

        card.addEventListener("click", () => {
            this.store?.set("context.project", {
                id:   project.id,
                name: project.name,
                code: project.code || "",
            });
        });

        return card;
    }

    createStat(label, value) {

        return `
            <div class="cpm-stat">

                <span class="cpm-stat-label">
                    ${label}
                </span>

                <span class="cpm-stat-value">
                    ${value || 0}
                </span>

            </div>
        `;
    }
}

export default CpmProjectView;

viewRegistry.register("cpm", CpmProjectView);
