import {
  Tabulator,
  SortModule,
  FilterModule,
  PageModule,
  AjaxModule,
  FormatModule,
  InteractionModule,
} from "/wp-content/plugins/acc-engine/tabulator-master/dist/js/tabulator_esm.js";

import { Runtime } from "../../runtime/runtime.js";
import { CardRenderer } from "../../runtime/CardRenderer.js";

Tabulator.registerModule([
  SortModule,
  FilterModule,
  PageModule,
  AjaxModule,
  FormatModule,
  InteractionModule,
]);

export default class ProjectsTable {
  constructor({ api, schema, store = null, eventBus = null }) {
    this.api = api;
    this.schema = schema;
    this.store = store;
    this.eventBus = eventBus;
    this.table = null;
    this.currentSearchTerm = "";
    this._selectedId = null;
  }

  // --- متد جدید برای آماده‌سازی دیتا بدون خراب کردن آی‌دی‌ها ---
  _prepareRecord(record) {
    if (!record) return record;

    const newRecord = { ...record };

    // اگر مقدار status_id به صورت string ترکیبی است (مثلاً "5 – Cancelled")
    if (
      typeof newRecord.status_id === "string" &&
      newRecord.status_id.includes("–")
    ) {
      const parts = newRecord.status_id.split("–");
      // مقدار عددی و مقدار نمایشی استخراج شود
      newRecord.status_id = parseInt(parts[0].trim());
      newRecord.status_id_label = parts[1].trim();
    }

    // اگر مقدار phase_id به همین شکل است
    if (
      typeof newRecord.phase_id === "string" &&
      newRecord.phase_id.includes("–")
    ) {
      const parts = newRecord.phase_id.split("–");
      newRecord.phase_id = parseInt(parts[0].trim());
      newRecord.phase_id_label = parts[1].trim();
    }

    // اگر مقدار lifecycle_stage_id هم همینطور است - اضافه کن اگر داری
    if (
      typeof newRecord.lifecycle_stage_id === "string" &&
      newRecord.lifecycle_stage_id.includes("–")
    ) {
      const parts = newRecord.lifecycle_stage_id.split("–");
      newRecord.lifecycle_stage_id = parseInt(parts[0].trim());
      newRecord.lifecycle_stage_id_label = parts[1].trim();
    }

    // اگر status آبجکت است (مثلاً {id: 5, title: "تکمیل شده"})
    if (
      newRecord.status &&
      typeof newRecord.status === "object" &&
      newRecord.status.title
    ) {
      newRecord.status_label = newRecord.status.title;
    }

    // همین منطق برای سایر relationها اجرا کن
    Object.keys(newRecord).forEach(key => {
      if (
        newRecord[key] &&
        typeof newRecord[key] === "object" &&
        newRecord[key].title
      ) {
        newRecord[key + "_label"] = newRecord[key].title;
      }
    });

    return newRecord;
  }


  mount(el) {
    this._injectStyles();

    const iconEdit = `<svg viewBox="0 0 24 24" width="18" height="18"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25z"/></svg>`;
    const iconDelete = `<svg viewBox="0 0 24 24" width="18" height="18"><path d="M6 7h12v12a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V7zm3-4h6l1 2H8l1-2z"/></svg>`;

    this.table = new Tabulator(el, {
      index: "id",
      height: "auto",
      layout: "fitColumns",
      headerVisible: false,
      pagination: true,
      paginationMode: "remote",
      paginationSize: 10,
      ajaxURL: "/runtime/projects/records",

      ajaxRequestFunc: async (url, config, params) => {
        const requestParams = {
          page: params.page || 1,
          size: params.size || 10,
          search: this.currentSearchTerm.trim(),
        };

        try {
          const response = await this.api.get("/runtime/projects/records", requestParams);

          // اصلاح این قسمت: پردازش رکوردها قبل از نمایش
          const rawData = response?.data ?? [];
          const processedData = rawData.map(item => this._prepareRecord(item));

          return {
            data: processedData,
            last_page: Math.max(
              1,
              Math.ceil((response?.pagination?.total || 0) / (params.size || 10))
            ),
          };
        } catch (err) {
          console.error("Fetch Error:", err);
          return { data: [], last_page: 1 };
        }
      },

      columns: [
        {
          field: "id",
          widthGrow: 1,
          formatter: (cell) => {
            const data = cell.getRow().getData();
            let cardHtml = "";

            try {
              // اینجا دیتای پردازش شده (دارای _label) به رندرر می‌رود
              cardHtml = CardRenderer.render(this.schema, data);
            } catch (e) {
              console.error("Render Error ID " + data.id, e);
              cardHtml = `<div style="color:red; padding:10px;">Error in CardRenderer</div>`;
            }

            return `
              <div class="project-card-wrapper" style="width:100%; padding:2px;">
                <div class="project-card" style="background:#fff; border:1px solid #eee; border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,0.05); overflow:hidden;">
                    <div class="card-body" style="padding:15px;">${cardHtml}</div>
                    <div class="card-footer" style="background:#f9f9f9; padding:10px 15px; display:flex; justify-content:flex-end; gap:10px; border-top:1px solid #eee;">
                       <button class="edit-trigger" title="ویرایش" style="border:none; background:none; cursor:pointer; fill:#1a73e8; padding:5px;">${iconEdit}</button>
                       <button class="delete-trigger" title="حذف" style="border:none; background:none; cursor:pointer; fill:#d93025; padding:5px;">${iconDelete}</button>
                    </div>
                </div>
              </div>`;
          }
        },
      ],
    });

    this.table.on("cellClick", (e, cell) => {
      const data   = cell.getRow().getData();
      const target = e.target.closest("button");

      if (target?.classList.contains("edit-trigger")) {
        Runtime.bus.emit("project-edit-requested", { id: data.id, record: data });
        return;
      }

      if (target?.classList.contains("delete-trigger")) {
        Runtime.bus.emit("project-delete-requested", { id: data.id });
        return;
      }

      // کلیک روی بدنه کارت → انتخاب به عنوان context فعال
      this._selectProject(data);
    });
  }

  _selectProject(data) {
    if (!data?.id) return;

    this._selectedId = data.id;

    // به‌روزرسانی Store — EventBus خودکار fire می‌شود
    if (this.store) {
      this.store.set("context.project", data);
    }

    // حالت بصری: هایلایت کارت انتخاب‌شده
    this._updateSelectionVisual(data.id);
  }

  _updateSelectionVisual(selectedId) {
    if (!this.table) return;
    this.table.getRows().forEach((row) => {
      const rowData = row.getData();
      const el = row.getElement();
      if (!el) return;
      el.classList.toggle("project-card--selected", rowData.id === selectedId);
    });
  }

  search(val) {
    this.currentSearchTerm = (val || "").trim();
    if (!this.table) return;
    this.table.setPage(1);
    this.table.setData("/runtime/projects/records");
  }

  updateRow(id, data) {
    if (!this.table) return;
    const row = this.table.getRow(id);
    if (row) {
      // اینجا هم دیتا را قبل از آپدیت سطر آماده می‌کنیم
      row.update(this._prepareRecord(data));
    } else {
      this.reload();
    }
  }

  deleteRow(id) {
    if (!this.table) return;
    const row = this.table.getRow(id);
    if (row) row.delete();
  }

  reload() {
    if (!this.table) return;
    this.table.setData("/runtime/projects/records");
  }

  _injectStyles() {
    if (document.getElementById("projects-table-styles")) return;
    const style = document.createElement("style");
    style.id = "projects-table-styles";
    style.innerHTML = `
      .tabulator { border:none !important; background:transparent !important; font-family: inherit !important; }
      .tabulator-tableholder { overflow-x: hidden !important; }
      .tabulator-row { display: block !important; width: 100% !important; margin-bottom: 15px !important; background: transparent !important; border: none !important; }
      .tabulator-cell { width: 100% !important; display: block !important; padding: 0 !important; border: none !important; }
      .project-card { transition: all 0.3s ease; cursor: pointer; }
      .project-card:hover { transform: translateY(-3px); box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important; }
      .tabulator-row.project-card--selected .project-card { border: 2px solid #1a73e8 !important; box-shadow: 0 0 0 3px rgba(26,115,232,0.15) !important; }
      .tabulator-row.project-card--selected .project-card::before { content: "✓ انتخاب شده"; display:block; background:#1a73e8; color:#fff; font-size:11px; padding:2px 10px; text-align:right; }
    `;
    document.head.appendChild(style);
  }

  destroy() {
    this.table?.destroy();
  }
}
