import React, { useEffect, useState, useCallback, useMemo, useRef } from "react";
import { apiCall } from "../../_services/apiCall";
import config from "../../config/config.json";
import Loader from "../loader/Loader";
import { Modal, ModalHeader } from "../../globalComponents/ui/Modal";
import { SecondaryButton } from "../../globalComponents/ui/Button";
import SimpleDropdown from "../../globalComponents/form/dropdowns/SimpleDropdown";
import { getLatestFY } from "../DataManagment/Quantative/component/answerHistoryPage/components/utils";
import {
  SettingsPage,
  SettingsTopBar, SettingsTopBarLeft, SettingsTopBarRight,
  SettingsAccentBar, SettingsTopBarTitle, SettingsTopBarSub,
  SettingsContent,
  SettingsCard, SettingsSectionHeader, SettingsSectionTitle, SettingsCountChip,
  SettingsFilterCard,
  SettingsModalBody, SettingsModalFooter,
} from "./SettingShell";
import TagFilterBar from "./Components/TagFilterBar";
import { questionMatchesSteps } from "./Components/TagFilterUtils";
import { safeParseJSON } from "./KpiAssets/helpers";

/* ─── helpers ───────────────────────────────────────────────────────────── */

function scopeColor(scope) {
  const s = (scope || "").toLowerCase();
  if (s.includes("1")) return { bg: "#fef3c7", text: "#92400e", border: "#fcd34d" };
  if (s.includes("2")) return { bg: "#dbeafe", text: "#1e40af", border: "#93c5fd" };
  if (s.includes("3")) return { bg: "#dcfce7", text: "#166534", border: "#86efac" };
  return { bg: "#f1f5f9", text: "#475569", border: "#e2e8f0" };
}

/* ─── Emission Factors Modal ────────────────────────────────────────────── */

function FactorsModal({ kpi, dataBaseList, onClose }) {
  const [loading, setLoading] = useState(true);
  const [factors, setFactors] = useState([]);
  const [search, setSearch] = useState("");

  useEffect(() => {
    if (!kpi) return;
    setLoading(true);
    setFactors([]);
    apiCall(
      `${config.POSTLOGIN_API_URL_COMPANY}getGHGEmissionFactors`,
      {},
      { kpi_id: kpi.questionId },
      "GET"
    ).then(({ isSuccess, data }) => {
      if (isSuccess && Array.isArray(data?.data)) setFactors(data.data);
    }).catch(console.error)
      .finally(() => setLoading(false));
  }, [kpi?.questionId]);

  const dbMap = useMemo(() => {
    const m = {};
    dataBaseList.forEach(raw => {
      // Sequelize may wrap fields in dataValues — unwrap if needed
      const db = raw?.dataValues ?? raw;
      if (db.id != null) m[db.id] = db.name;
    });
    return m;
  }, [dataBaseList]);

  const filtered = useMemo(() => {
    if (!search.trim()) return factors;
    const s = search.toLowerCase();
    return factors.filter(f =>
      (f.scope || "").toLowerCase().includes(s) ||
      (f.unit || "").toLowerCase().includes(s) ||
      (f.country_code || "").toLowerCase().includes(s) ||
      String(f.emission_factor).includes(s) ||
      (dbMap[f.ghg_database_id] || "").toLowerCase().includes(s)
    );
  }, [factors, search, dbMap]);

  /* group by ghg_database_id */
  const grouped = useMemo(() => {
    const map = new Map();
    filtered.forEach(f => {
      const key = f.ghg_database_id;
      if (!map.has(key)) map.set(key, []);
      map.get(key).push(f);
    });
    return map;
  }, [filtered]);

  return (
    <Modal show={!!kpi} onClose={onClose} maxWidth={1000}>
      <ModalHeader
        icon="fas fa-layer-group"
        title={kpi?.title || "Emission Factors"}
      />
      <SettingsModalBody style={{ padding: 0, maxHeight: "78vh", overflowY: "auto" }}>

        {/* KPI meta strip */}
        <div style={{
          display: "flex", alignItems: "center", gap: 10,
          padding: "14px 20px", background: "#f8fafc",
          borderBottom: "1px solid #e2e8f0"
        }}>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#1e293b", flex: 1 }}>{kpi?.title}</span>
          <span style={{
            fontSize: 11, fontWeight: 700,
            background: "#f1f5f9", color: "#475569",
            padding: "3px 10px", borderRadius: 20,
            border: "1px solid #e2e8f0"
          }}>
            {loading ? "…" : `${factors.length} factor${factors.length !== 1 ? "s" : ""}`}
          </span>
        </div>

        {/* search */}
        <div style={{ padding: "12px 20px", borderBottom: "1px solid #f1f5f9" }}>
          <div style={{ position: "relative" }}>
            <i className="fas fa-search" style={{
              position: "absolute", left: 12, top: "50%",
              transform: "translateY(-50%)", color: "#94a3b8", fontSize: 12
            }} />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Filter by scope, unit, country, database…"
              style={{
                width: "100%", padding: "8px 12px 8px 34px",
                border: "1.5px solid #e2e8f0", borderRadius: 8,
                fontSize: 12.5, outline: "none", boxSizing: "border-box"
              }}
            />
          </div>
        </div>

        {/* body */}
        <div style={{ padding: "16px 20px" }}>
          {loading ? (
            <div style={{ display: "flex", justifyContent: "center", padding: "50px 0" }}>
              <Loader />
            </div>
          ) : factors.length === 0 ? (
            <div style={{
              textAlign: "center", padding: "48px 0",
              color: "#94a3b8", fontSize: 13,
              border: "1.5px dashed #e2e8f0", borderRadius: 12
            }}>
              <i className="fas fa-database" style={{ fontSize: 24, marginBottom: 10, display: "block", color: "#cbd5e1" }} />
              No emission factors found for this KPI.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              {Array.from(grouped.entries()).map(([dbId, rows]) => {
                const dbName = dbMap[dbId] || `Database #${dbId}`;
                return (
                  <div key={dbId} style={{
                    border: "1px solid #e2e8f0", borderRadius: 12,
                    overflow: "hidden"
                  }}>
                    {/* DB group header */}
                    <div style={{
                      display: "flex", alignItems: "center", gap: 8,
                      padding: "10px 16px", background: "#f8fafc",
                      borderBottom: "1px solid #e2e8f0"
                    }}>
                      <i className="fas fa-database" style={{ fontSize: 11, color: "#3f88a5" }} />
                      <span style={{ fontSize: 12, fontWeight: 700, color: "#334155" }}>{dbName}</span>
                      <span style={{
                        marginLeft: "auto", fontSize: 10, fontWeight: 700,
                        background: "#e0f2fe", color: "#0369a1",
                        padding: "1px 7px", borderRadius: 10
                      }}>{rows.length} {rows.length === 1 ? "record" : "records"}</span>
                    </div>

                    {/* table */}
                    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
                      <thead>
                        <tr style={{ background: "#fafafa" }}>
                          {["Scope", "Country", "Unit", "Emission Factor", "GHG Database", "Formula"].map(h => (
                            <th key={h} style={{
                              padding: "9px 14px", fontWeight: 700,
                              color: "#64748b", textAlign: "left",
                              borderBottom: "1px solid #f1f5f9",
                              fontSize: 11, textTransform: "uppercase", letterSpacing: "0.4px"
                            }}>{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {rows.map((f, idx) => {
                          const sc = scopeColor(f.scope);
                          return (
                            <tr
                              key={f.id || idx}
                              style={{ borderBottom: idx === rows.length - 1 ? "none" : "1px solid #f8fafc" }}
                              onMouseEnter={e => e.currentTarget.style.background = "#f8fafc"}
                              onMouseLeave={e => e.currentTarget.style.background = ""}
                            >
                              <td style={{ padding: "10px 14px" }}>
                                <span style={{
                                  fontSize: 10.5, fontWeight: 700,
                                  background: sc.bg, color: sc.text,
                                  border: `1px solid ${sc.border}`,
                                  padding: "2px 8px", borderRadius: 20
                                }}>{f.scope || "N/A"}</span>
                              </td>
                              <td style={{ padding: "10px 14px" }}>
                                <span style={{
                                  fontSize: 11, fontWeight: 700,
                                  background: "#f1f5f9", color: "#475569",
                                  border: "1px solid #e2e8f0",
                                  padding: "2px 7px", borderRadius: 4
                                }}>{f.country_code || "—"}</span>
                              </td>
                              <td style={{
                                padding: "10px 14px", fontFamily: "monospace",
                                fontWeight: 600, color: "#1e293b", fontSize: 12
                              }}>{f.unit || "—"}</td>
                              <td style={{ padding: "10px 14px" }}>
                                <span style={{
                                  fontWeight: 700, color: "#0f172a", fontSize: 13,
                                  fontFamily: "monospace"
                                }}>
                                  {Number(f.emission_factor).toFixed(7)}
                                </span>
                              </td>
                              {/* GHG Database name */}
                              <td style={{ padding: "10px 14px" }}>
                                <span style={{
                                  fontSize: 11, fontWeight: 600,
                                  background: "#eff6ff", color: "#1d4ed8",
                                  border: "1px solid #bfdbfe",
                                  padding: "2px 8px", borderRadius: 6
                                }}>
                                  {dbMap[f.ghg_database_id] || `DB #${f.ghg_database_id}`}
                                </span>
                              </td>
                              {/* Formula */}
                              <td style={{ padding: "10px 14px" }}>
                                <code style={{
                                  fontSize: 11, color: "#475569",
                                  background: "#f8fafc", border: "1px solid #e2e8f0",
                                  borderRadius: 5, padding: "3px 8px",
                                  whiteSpace: "nowrap", display: "block"
                                }}>
                                  Q ({f.unit || "unit"}) × {Number(f.emission_factor).toFixed(5)} = kgCO₂e
                                </code>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </SettingsModalBody>
      <SettingsModalFooter>
        <SecondaryButton onClick={onClose}>Close</SecondaryButton>
      </SettingsModalFooter>
    </Modal>
  );
}

/* ─── Main component ────────────────────────────────────────────────────── */

const Emission = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [allKpis, setAllKpis] = useState([]);
  const [dataBaseList, setDataBaseList] = useState([]);
  const [selectedKpi, setSelectedKpi] = useState(null);
  const [search, setSearch] = useState("");
  const [filterSteps, setFilterSteps] = useState([]);

  /** Financial years come from localStorage once, at mount. */
  const [fyData] = useState(() => safeParseJSON(localStorage.getItem("financialYears"), []));
  /**
   * Chronologically newest financial year — the page's default selection.
   * Labelled "(Latest)" rather than "(Current)" because it is not the
   * company's `active` reporting year, which may be an older one.
   */
  const latestFY = useMemo(() => getLatestFY(fyData), [fyData]);
  const [selectedFY, setSelectedFY] = useState(() => latestFY);

  const fyOptions = useMemo(() =>
    fyData.map(fy => ({
      value: fy.id,
      label: `${fy.financial_year_value}${fy.id === latestFY?.id ? " (Latest)" : ""}`,
    })),
    [fyData, latestFY]
  );

  /** Guards against a slower response from a previously selected financial year. */
  const fetchIdRef = useRef(0);

  /**
   * GHG database names and framework ids don't vary by financial year, so the
   * request is issued once and the promise reused across year switches. A
   * rejected attempt clears the cache so Retry fetches it again.
   */
  const refDataRef = useRef(null);
  const loadRefData = useCallback(() => {
    if (refDataRef.current) return refDataRef.current;

    const pending = (async () => {
      const userId = JSON.parse(localStorage.getItem("user_temp_id"));
      const [dbRes, fwRes] = await Promise.all([
        apiCall(`${config.POSTLOGIN_API_URL_COMPANY}ghg/databases`, {}, {}, "GET"),
        apiCall(`${config.POSTLOGIN_API_URL_COMPANY}getFramework`, {}, { type: "ALL", userId }, "GET"),
      ]);
      return {
        dataBaseList: dbRes?.data?.dataBaseList || dbRes?.data?.data?.dataBaseList || [],
        frameworkIds: (fwRes.data?.data || []).map(f => f.id),
      };
    })();

    refDataRef.current = pending.catch(err => {
      refDataRef.current = null;
      throw err;
    });
    return refDataRef.current;
  }, []);

  /** Loads the emission-enabled KPI list for `selectedFY`. */
  const fetchAll = useCallback(async () => {
    const fyId = selectedFY?.id;
    const fetchId = ++fetchIdRef.current;
    const isStale = () => fetchIdRef.current !== fetchId;

    if (!fyId) {
      setAllKpis([]);
      setLoading(false);
      return;
    }

    setLoading(true);
    setError("");
    try {
      const [refData, settingsRes] = await Promise.all([
        loadRefData(),
        apiCall(`${config.POSTLOGIN_API_URL_COMPANY}emissionKpiSettings`, {}, { fyid: fyId }, "GET"),
      ]);
      if (isStale()) return;
      setDataBaseList(refData.dataBaseList);

      const qRes = await apiCall(
        `${config.POSTLOGIN_API_URL_COMPANY}getReportingQuestionnew`, {},
        {
          financialYearId: fyId,
          frameworkIds: refData.frameworkIds,
          fromSettings: true,
          question_type_filter: JSON.stringify(["quantitative"]),
        },
        "GET"
      );
      if (isStale()) return;
      const questions = qRes.data?.data || [];

      const raw = settingsRes.data;
      const savedKIds = Array.isArray(raw?.kpiIds) ? raw.kpiIds.map(Number) : [];
      const validIds = new Set(questions.map(q => q.questionId));

      const enabledIds = raw?.id && savedKIds.length > 0
        ? new Set(savedKIds.filter(id => validIds.has(id)))
        : new Set(questions.filter(q => q.kpi_type?.includes("EMISSION")).map(q => q.questionId));

      setAllKpis(questions.filter(q => enabledIds.has(q.questionId)));
    } catch (e) {
      if (isStale()) return;
      console.error("Emission fetch error", e);
      setAllKpis([]);
      setError("Could not load emission KPIs for this financial year.");
    } finally {
      if (!isStale()) setLoading(false);
    }
  }, [selectedFY?.id, loadRefData]);

  useEffect(() => { fetchAll(); }, [fetchAll]);

  /** Switching year invalidates staged filters, the search term and the open modal. */
  const handleFYChange = useCallback((val) => {
    const found = fyData.find(f => String(f.id) === String(val));
    if (!found) return;
    setSelectedFY(found);
    setFilterSteps([]);
    setSearch("");
    setSelectedKpi(null);
  }, [fyData]);

  /* ── filtered list ──────────────────────────────────────────────────── */
  const filtered = useMemo(() => {
    let result = allKpis;
    if (search.trim()) {
      const s = search.toLowerCase();
      result = result.filter(k => (k.title || "").toLowerCase().includes(s));
    }
    if (filterSteps && filterSteps.some(s => s.values?.size > 0)) {
      result = result.filter(k => questionMatchesSteps(k, filterSteps));
    }
    return result;
  }, [allKpis, search, filterSteps]);

  /* ── render ─────────────────────────────────────────────────────────── */
  return (
    <SettingsPage>
      <SettingsTopBar>
        <SettingsTopBarLeft>
          <SettingsAccentBar />
          <div>
            <SettingsTopBarTitle>Emission Factors</SettingsTopBarTitle>
            <SettingsTopBarSub>
              View all emission factors associated with each emission KPI
              {selectedFY?.financial_year_value ? ` · FY ${selectedFY.financial_year_value}` : ""}
            </SettingsTopBarSub>
          </div>
        </SettingsTopBarLeft>

        {fyOptions.length > 0 && (
          <SettingsTopBarRight>
            <SimpleDropdown
              label="Financial Year"
              value={selectedFY?.id ?? ""}
              onChange={handleFYChange}
              options={fyOptions}
              isAlert={selectedFY?.id !== latestFY?.id}
            />
          </SettingsTopBarRight>
        )}
      </SettingsTopBar>

      <SettingsContent $wide>
        {/* search bar */}
        <SettingsFilterCard>
          <div style={{ display: "flex", flexDirection: "column", width: "100%" }}>
            <div style={{ position: "relative", flex: 1 }}>
              <i className="fas fa-search" style={{
                position: "absolute", left: 14, top: "50%",
                transform: "translateY(-50%)", color: "#94a3b8", fontSize: 13
              }} />
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search KPI by title…"
                style={{
                  width: "100%", padding: "9px 14px 9px 38px",
                  border: "1.5px solid #e2e8f0", borderRadius: 10,
                  fontSize: 13, outline: "none", boxSizing: "border-box",
                  marginBottom: filterSteps.length > 0 || allKpis.length > 0 ? 12 : 0
                }}
              />
            </div>
            <TagFilterBar
              allQuestions={allKpis}
              filterSteps={filterSteps}
              onFilterStepsChange={setFilterSteps}
              disableAllSelected={true}
            />
          </div>
        </SettingsFilterCard>

        {/* KPI list card */}
        <SettingsCard>
          <SettingsSectionHeader>
            <i className="fas fa-layer-group" style={{ fontSize: 12, color: "#3f88a5" }} />
            <SettingsSectionTitle>KPI Emission Factors</SettingsSectionTitle>
            <SettingsCountChip>{filtered.length}</SettingsCountChip>
          </SettingsSectionHeader>

          {loading ? (
            <div style={{ padding: 60, display: "flex", justifyContent: "center" }}>
              <Loader />
            </div>
          ) : error ? (
            <div style={{
              padding: "48px 0", textAlign: "center",
              color: "#b91c1c", fontSize: 13
            }}>
              <i className="fas fa-triangle-exclamation" style={{ fontSize: 28, marginBottom: 10, display: "block", color: "#fca5a5" }} />
              {error}
              <div style={{ marginTop: 14 }}>
                <SecondaryButton onClick={fetchAll}>Retry</SecondaryButton>
              </div>
            </div>
          ) : filtered.length === 0 ? (
            <div style={{
              padding: "48px 0", textAlign: "center",
              color: "#94a3b8", fontSize: 13
            }}>
              <i className="fas fa-leaf" style={{ fontSize: 28, marginBottom: 10, display: "block", color: "#cbd5e1" }} />
              No emission KPIs found
              {selectedFY?.financial_year_value ? ` for FY ${selectedFY.financial_year_value}` : ""}.
              {" "}Configure them in the <strong>KPIs</strong> settings tab.
            </div>
          ) : (
            <div>
              {/* table header */}
              <div style={{
                display: "grid",
                gridTemplateColumns: "50px 1fr 140px",
                padding: "10px 20px",
                background: "#f8fafc",
                borderBottom: "1px solid #e2e8f0",
              }}>
                {["#", "KPI Title", "Action"].map(h => (
                  <span key={h} style={{
                    fontSize: 10.5, fontWeight: 700, color: "#64748b",
                    textTransform: "uppercase", letterSpacing: "0.5px"
                  }}>{h}</span>
                ))}
              </div>

              {/* rows */}
              {filtered.map((kpi, idx) => (
                <div
                  key={kpi.questionId}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "50px 1fr 140px",
                    alignItems: "center",
                    padding: "13px 20px",
                    borderBottom: idx === filtered.length - 1 ? "none" : "1px solid #f1f5f9",
                    background: "#fff",
                    transition: "background 0.1s",
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = "#f8fafc"}
                  onMouseLeave={e => e.currentTarget.style.background = "#fff"}
                >
                  {/* index */}
                  <span style={{ fontSize: 12, color: "#94a3b8", fontWeight: 600 }}>
                    {idx + 1}
                  </span>

                  {/* title */}
                  <div style={{ minWidth: 0, paddingRight: 16 }}>
                    <div style={{
                      fontSize: 13, fontWeight: 600, color: "#1e293b",
                      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
                    }} title={kpi.title}>
                      {kpi.title ? kpi.title.replace(/^\[.*?\]\s*/, "") : "—"}
                    </div>
                    {kpi.kpi_type && (
                      <div style={{ marginTop: 3, display: "flex", gap: 4, flexWrap: "wrap" }}>
                        {(Array.isArray(kpi.kpi_type) ? kpi.kpi_type : [kpi.kpi_type])
                          .filter(Boolean)
                          .map(t => (
                            <span key={t} style={{
                              fontSize: 9.5, fontWeight: 700,
                              background: t.includes("EMISSION") ? "#fef3c7" : "#f1f5f9",
                              color: t.includes("EMISSION") ? "#92400e" : "#475569",
                              border: `1px solid ${t.includes("EMISSION") ? "#fcd34d" : "#e2e8f0"}`,
                              padding: "1px 6px", borderRadius: 20
                            }}>{t}</span>
                          ))}
                      </div>
                    )}
                  </div>

                  {/* action */}
                  <button
                    onClick={() => setSelectedKpi(kpi)}
                    style={{
                      display: "inline-flex", alignItems: "center", gap: 6,
                      padding: "7px 14px", borderRadius: 8,
                      border: "1.5px solid #e2e8f0",
                      background: "#fff", cursor: "pointer",
                      fontSize: 11.5, fontWeight: 700, color: "#3f88a5",
                      transition: "all 0.15s",
                    }}
                    onMouseEnter={e => {
                      e.currentTarget.style.background = "#e0f2fe";
                      e.currentTarget.style.borderColor = "#7dd3fc";
                    }}
                    onMouseLeave={e => {
                      e.currentTarget.style.background = "#fff";
                      e.currentTarget.style.borderColor = "#e2e8f0";
                    }}
                  >
                    <i className="fas fa-layer-group" style={{ fontSize: 10 }} />
                    View Factors
                  </button>
                </div>
              ))}
            </div>
          )}
        </SettingsCard>
      </SettingsContent>

      {/* Factors modal */}
      <FactorsModal
        kpi={selectedKpi}
        dataBaseList={dataBaseList}
        onClose={() => setSelectedKpi(null)}
      />
    </SettingsPage>
  );
};

export default Emission;
