import BaseView from "../../../core/BaseView.js";
import { viewRegistry } from "../../../core/registries.js";
import { runtimeStore } from "../../../core/RuntimeStore.js"; // اضافه شد

import SchemaLoader from "../../runtime/SchemaLoader.js";

import ProjectsDataSource from "../table/ProjectsDataSource.js";
import ProjectsRenderer from "../table/ProjectsRenderer.js";
import ProjectsPaginator from "../table/ProjectsPaginator.js";

import ProjectsToolbar from "../../runtime/toolbar/ProjectsToolbar.js";
import ProjectEditModal from "../../runtime/modal/ProjectEditModal.js";

class ProjectsRuntimeView extends BaseView {

    static title = "Dynamic Runtime Explorer";

    constructor(props = {}) {
        super(props);

        this.api = props.api;
        this.schemaLoader = new SchemaLoader(this.api);

        this.dataSource = null;
        this.renderer = null;
        this.paginator = null;
        this.toolbar = null;
        this.modal = null;

        this.availableSchemas = [
            { id: "projects", title: "پروژه‌ها", icon: "🏢" },
            { id: "lands", title: "زمین‌ها", icon: "🗺️" },
            { id: "units", title: "واحدها", icon: "🏠" }
        ];

        this.currentSlug = "projects";
    }

    async render(container) {
        await super.render(container);
        const body = this.ref("body");

        body.innerHTML = `
        <style>
            .runtime-layout-container {
                display: flex;
                height: 100%;
                background: #f9fafb;
                position: relative;
            }

            .runtime-sidebar {
                width: 240px;
                background: #fff;
                border-left: 1px solid #e5e7eb;
                transition: width 0.3s ease;
                overflow: hidden;
                flex-shrink: 0;
            }

            .runtime-sidebar.collapsed {
                width: 0;
                border: none;
            }

            .sidebar-inner {
                padding: 15px;
                width: 240px;
            }

            .schema-item {
                padding: 12px;
                margin-bottom: 8px;
                border-radius: 8px;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 10px;
                border: 1px solid transparent;
                transition: all 0.2s;
            }

            .schema-item:hover {
                background: #f3f4f6;
                border-color: #d1d5db;
                transform: translateX(4px);
            }

            .schema-item.active {
                background: #eff6ff;
                border-color: #3b82f6;
                color: #1d4ed8;
            }

            .sidebar-toggle {
                position: absolute;
                top: 20px;
                left: 240px;
                z-index: 20;
                background: #fff;
                border: 1px solid #e5e7eb;
                border-radius: 0 8px 8px 0;
                padding: 6px 10px;
                cursor: pointer;
                transition: left 0.3s ease;
            }

            .runtime-sidebar.collapsed + .sidebar-toggle {
                left: 0;
            }
        </style>

        <div class="runtime-layout-container">
            <div class="runtime-sidebar" id="runtimeSidebar">
                <div class="sidebar-inner">
                    <h4 style="margin-bottom:16px;font-size:13px;color:#6b7280;border-bottom:1px solid #eee;padding-bottom:8px">
                        انتخاب موجودیت
                    </h4>

                    <div class="schema-switcher-list">
                        ${this.availableSchemas.map(item => `
                            <div class="schema-item ${item.id === this.currentSlug ? "active" : ""}"
                                 data-slug="${item.id}">
                                <span>${item.icon}</span>
                                <span style="font-weight:500">${item.title}</span>
                            </div>
                        `).join("")}
                    </div>
                </div>
            </div>

            <button class="sidebar-toggle" id="sidebarToggle">☰</button>

            <div class="runtime-main-content" style="flex:1;padding:20px;overflow-y:auto">
                <div class="projects-runtime-wrapper">
                    <div class="projects-runtime-toolbar" style="margin-bottom:12px"></div>
                    <div class="projects-runtime-list"></div>
                    <div class="projects-runtime-pagination" style="margin-top:10px"></div>
                </div>
            </div>
        </div>
        `;

        const sidebar = body.querySelector("#runtimeSidebar");
        const toggleBtn = body.querySelector("#sidebarToggle");

        toggleBtn.onclick = () => {
            sidebar.classList.toggle("collapsed");
            toggleBtn.textContent = sidebar.classList.contains("collapsed") ? "→" : "☰";
        };

        body.querySelectorAll(".schema-item").forEach(el => {
            el.onclick = () => this.switchTo(el.dataset.slug);
        });

        await this.switchTo(this.currentSlug);
        return this;
    }

    async switchTo(slug) {
        this.currentSlug = slug;

        this.ref("body").querySelectorAll(".schema-item").forEach(el => {
            el.classList.toggle("active", el.dataset.slug === slug);
        });

        const listContainer = this.ref("body").querySelector(".projects-runtime-list");

        listContainer.innerHTML =
            `<div style="padding:40px;text-align:center;color:#9ca3af">
                در حال بارگذاری ${slug}...
             </div>`;

        try {
            const schema = await this.schemaLoader.load(slug);

            this.dataSource = new ProjectsDataSource({
                api: this.api,
                endpoint: `/runtime/${slug}/records`,
                pageSize: 10
            });

            this.renderer = new ProjectsRenderer({
                schema,
                onEdit: id => this.handleEdit(id),
                onDelete: id => this.handleDelete(id),
                // افزودن قابلیت انتخاب پروژه:
                onSelect: id => {
                    runtimeStore.set('active_project_id', id);
                    // رندر مجدد برای آپدیت رنگ ستاره فعال در UI
                    this.renderer.render(this.dataSource.records);
                }
            });

            listContainer.innerHTML = "";
            this.renderer.mount(listContainer);

            const paginatorContainer = this.ref("body").querySelector(".projects-runtime-pagination");

            this.paginator = new ProjectsPaginator({
                container: paginatorContainer,
                dataSource: this.dataSource
            });

            this.paginator.mount();

            this.dataSource.onDataLoaded = ({ records }) => {
                this.renderer.render(records);
                this.paginator.update();
            };

            this.setupComponents(schema);
            await this.dataSource.loadPage(1);

        } catch (err) {
            console.error(err);
            listContainer.innerHTML =
                `<div style="color:red;padding:20px">
                    خطا در بارگذاری ${slug}
                 </div>`;
        }
    }

    setupComponents(schema) {
        const toolbarContainer = this.ref("body").querySelector(".projects-runtime-toolbar");

        const tableAdapter = {
            setSearch: term => this.dataSource.setSearch(term),
            reload: () => this.dataSource.reload(),
            create: () => this.handleCreate()
        };

        this.toolbar = new ProjectsToolbar({ table: tableAdapter });
        toolbarContainer.innerHTML = "";
        this.toolbar.mount(toolbarContainer);

        this.modal = new ProjectEditModal({
            api: this.api,
            schema,
            onSaved: () => this.dataSource.reload()
        });

        this.modal.mount(document.body);
    }

    handleCreate() {
        this.modal?.open({ mode: "create" });
    }

    handleEdit(id) {
        const record = this.dataSource.records.find(r => String(r.id) === String(id));
        if (record) {
            this.modal.open({ mode: "edit", id: record.id, record });
        }
    }

    async handleDelete(id) {
        if (!confirm("آیا از حذف مطمئن هستید؟")) return;
        await this.api.delete(`/runtime/${this.currentSlug}/records/${id}`);
        this.dataSource.deleteRecord(id);
        this.renderer.render(this.dataSource.records);
    }

    destroy() {
        this.dataSource?.destroy?.();
        this.renderer?.destroy?.();
        this.paginator?.destroy?.();
        this.toolbar?.destroy?.();
        this.modal?.destroy?.();
        super.destroy();
    }
}

viewRegistry.register("lands", ProjectsRuntimeView);
export default ProjectsRuntimeView;
