import { db } from "./firebase-config.js";
import { requireAuth, setupLogoutButton } from "./app-guard.js";
import { showLoader, hideLoader } from "./loader.js";
import { showToast } from "./toast.js";

import {
  collection,
  getDocs,
  query,
  where
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const trainingLoadTeamFilter = document.getElementById("trainingLoadTeamFilter");
const trainingLoadList = document.getElementById("trainingLoadList");

const loadTotalSessions = document.getElementById("loadTotalSessions");
const loadAverageSession = document.getElementById("loadAverageSession");
const loadHighSessions = document.getElementById("loadHighSessions");
const loadOverloadSessions = document.getElementById("loadOverloadSessions");

const exportTrainingLoadCsvBtn = document.getElementById("exportTrainingLoadCsvBtn");
const printTrainingLoadBtn = document.getElementById("printTrainingLoadBtn");

let activeProfile = null;
let teamsCache = [];
let sessionsCache = [];

function canAccessTeam(teamId) {
  if (!activeProfile || !teamId) return false;

  const role = activeProfile.role;
  const assignedTeamIds = activeProfile.assignedTeamIds || [];

  if (role === "director") return true;

  if (role === "coach" || role === "biokineticist") {
    return assignedTeamIds.includes(teamId);
  }

  return false;
}

async function getRecords(collectionName) {
  const q = query(
    collection(db, collectionName),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const snapshot = await getDocs(q);

  return snapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));
}

function getTeamName(teamId) {
  const team = teamsCache.find((item) => item.id === teamId);
  return team ? team.name : "Unassigned";
}

function getLoadStatus(load) {
  if (load >= 500) return "Overload Risk";
  if (load >= 350) return "High Load";
  if (load >= 180) return "Optimal";
  return "Low Load";
}

function getLoadClass(load) {
  if (load >= 500) return "readiness-danger";
  if (load >= 350) return "readiness-monitor";
  if (load >= 180) return "readiness-ready";

  return "readiness-monitor";
}

function sortSessions(sessions) {
  return [...sessions].sort((a, b) => {
    return new Date(b.date || "1900-01-01") - new Date(a.date || "1900-01-01");
  });
}

function getFilteredSessions() {
  const selectedTeam = trainingLoadTeamFilter.value || "all";

  const filteredSessions = sessionsCache.filter((session) => {
    return selectedTeam === "all" || session.teamId === selectedTeam;
  });

  return sortSessions(filteredSessions);
}

async function loadData() {
  trainingLoadList.innerHTML = `
    <div class="app-card">
      Loading training load report...
    </div>
  `;

  const [teams, sessions] = await Promise.all([
    getRecords("teams"),
    getRecords("trainingSessions")
  ]);

  teamsCache = teams.filter((team) => {
    return canAccessTeam(team.id);
  });

  sessionsCache = sessions.filter((session) => {
    return canAccessTeam(session.teamId);
  });

  sessionsCache = sortSessions(sessionsCache);

  renderTeamFilter();
  renderReport();
}

function renderTeamFilter() {
  trainingLoadTeamFilter.innerHTML = `
    <option value="all">All Teams</option>
  `;

  teamsCache.forEach((team) => {
    const option = document.createElement("option");

    option.value = team.id;
    option.textContent = `${team.name || "Unnamed Team"} • ${team.ageGroup || "No age group"}`;

    trainingLoadTeamFilter.appendChild(option);
  });
}

function renderReport() {
  const filteredSessions = getFilteredSessions();

  const totalSessions = filteredSessions.length;

  const totalLoad = filteredSessions.reduce((sum, session) => {
    return sum + Number(session.sessionLoad || 0);
  }, 0);

  const averageLoad = totalSessions
    ? Math.round(totalLoad / totalSessions)
    : 0;

  const highLoadCount = filteredSessions.filter((session) => {
    return Number(session.sessionLoad || 0) >= 350;
  }).length;

  const overloadCount = filteredSessions.filter((session) => {
    return Number(session.sessionLoad || 0) >= 500;
  }).length;

  loadTotalSessions.textContent = totalSessions;
  loadAverageSession.textContent = averageLoad;
  loadHighSessions.textContent = highLoadCount;
  loadOverloadSessions.textContent = overloadCount;

  trainingLoadList.innerHTML = "";

  if (!filteredSessions.length) {
    trainingLoadList.innerHTML = `
      <div class="app-card">
        No training sessions found.
      </div>
    `;

    return;
  }

  filteredSessions.forEach((session) => {
    const load = Number(session.sessionLoad || 0);

    const item = document.createElement("div");
    item.className = "elite-readiness-row elite-card";

    item.innerHTML = `
      <div>
        <h3>
          ${getTeamName(session.teamId)} • ${session.type || "Training"}
        </h3>

        <p>
          ${session.date || "No date"}

          <span class="record-separator">&bull;</span>

          ${session.time || "No time"}

          <span class="record-separator">&bull;</span>

          ${session.location || "No location"}
        </p>
      </div>

      <div class="report-metrics">
        <span class="report-pill ${getLoadClass(load)}">
          ${getLoadStatus(load)}
        </span>

        <span>Load: ${load}</span>

        <span>
          Duration: ${session.durationMinutes || 0} min
        </span>

        <span>
          Intensity: ${session.intensity || "-"}
        </span>
      </div>
    `;

    trainingLoadList.appendChild(item);
  });
}

function exportTrainingLoadCSV() {
  const filteredSessions = getFilteredSessions();

  let csvContent =
    "Team,Date,Time,Type,Location,Duration,Intensity,Load,Status\n";

  filteredSessions.forEach((session) => {
    const load = Number(session.sessionLoad || 0);

    const row = [
      `"${getTeamName(session.teamId)}"`,
      `"${session.date || ""}"`,
      `"${session.time || ""}"`,
      `"${session.type || ""}"`,
      `"${session.location || ""}"`,
      `"${session.durationMinutes || 0}"`,
      `"${session.intensity || ""}"`,
      `"${load}"`,
      `"${getLoadStatus(load)}"`
    ];

    csvContent += row.join(",") + "\n";
  });

  const blob = new Blob([csvContent], {
    type: "text/csv;charset=utf-8;"
  });

  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);

  link.setAttribute("href", url);

  link.setAttribute(
    "download",
    `training-load-${new Date().toISOString().slice(0, 10)}.csv`
  );

  link.style.visibility = "hidden";

  document.body.appendChild(link);

  link.click();

  document.body.removeChild(link);

  URL.revokeObjectURL(url);
}

trainingLoadTeamFilter?.addEventListener("change", renderReport);

printTrainingLoadBtn?.addEventListener("click", function () {
  window.print();
});

exportTrainingLoadCsvBtn?.addEventListener(
  "click",
  exportTrainingLoadCSV
);

requireAuth(async function (user, profile) {
  activeProfile = profile;

  setupLogoutButton();

  if (!activeProfile?.organisationId) {
    if (trainingLoadList) {
      trainingLoadList.innerHTML = `
        <div class="app-card">
          No organisation found for this user.
        </div>
      `;
    }

    return;
  }

  showLoader("Loading training load report...");

  try {
    await loadData();
  } catch (error) {
    console.error("Training load report error:", error);

    trainingLoadList.innerHTML = `
      <div class="app-card">
        Error loading training load report: ${error.message}
      </div>
    `;

    showToast(
      "Could not load training load report: " + error.message,
      "error"
    );
  } finally {
    hideLoader();
  }
});