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 {
  doc,
  getDoc,
  collection,
  getDocs,
  query,
  where
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const urlParams = new URLSearchParams(window.location.search);
const matchId = urlParams.get("id");

const teamSheetTitle = document.getElementById("teamSheetTitle");
const teamSheetMeta = document.getElementById("teamSheetMeta");

const startingTeamSheet = document.getElementById("startingTeamSheet");
const benchTeamSheet = document.getElementById("benchTeamSheet");

const printTeamSheetBtn = document.getElementById("printTeamSheetBtn");
const teamSheetNotes = document.getElementById("teamSheetNotes");

let activeProfile = null;
let currentMatch = null;
let latestSelection = null;

function canAccessMatch(match) {
  const role = activeProfile?.role;
  const assignedTeamIds = activeProfile?.assignedTeamIds || [];

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

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

  return false;
}

function getDateValue(record) {
  if (record?.updatedAt?.toDate) return record.updatedAt.toDate();
  if (record?.createdAt?.toDate) return record.createdAt.toDate();
  if (record?.updatedAt) return new Date(record.updatedAt);
  if (record?.createdAt) return new Date(record.createdAt);

  return new Date(0);
}

async function loadMatch() {
  const matchRef = doc(db, "matches", matchId);
  const matchSnap = await getDoc(matchRef);

  if (!matchSnap.exists()) {
    teamSheetTitle.textContent = "Match not found";
    return false;
  }

  currentMatch = {
    id: matchSnap.id,
    ...matchSnap.data()
  };

  if (currentMatch.organisationId !== activeProfile.organisationId) {
    showToast("This match does not belong to your organisation.", "error");
    window.location.href = "matches.html";
    return false;
  }

  if (!canAccessMatch(currentMatch)) {
    showToast("You do not have access to this team sheet.", "error");
    window.location.href = "matches.html";
    return false;
  }

  return true;
}

async function loadTeamSheet() {
  startingTeamSheet.innerHTML = `
    <div class="list-item">
      Loading team sheet...
    </div>
  `;

  benchTeamSheet.innerHTML = `
    <div class="list-item">
      Loading bench players...
    </div>
  `;

  const q = query(
    collection(db, "matchSelections"),
    where("matchId", "==", matchId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const snapshot = await getDocs(q);

  if (snapshot.empty) {
    teamSheetTitle.textContent = "No Team Sheet Found";

    teamSheetMeta.textContent = currentMatch
      ? `${currentMatch.date || "No date"} • ${currentMatch.venue || "No venue"}`
      : "No saved squad selection found.";

    startingTeamSheet.innerHTML = `
      <div class="list-item">
        No saved squad selections found.
      </div>
    `;

    benchTeamSheet.innerHTML = `
      <div class="list-item">
        No bench players selected.
      </div>
    `;

    teamSheetNotes.textContent = "No selection notes added.";
    return;
  }

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

  selections.sort((a, b) => getDateValue(b) - getDateValue(a));

  latestSelection = selections[0];

  renderTeamSheet();
}

function renderTeamSheet() {
  const teamName = latestSelection.teamName || currentMatch?.teamName || "Team";
  const opponent = latestSelection.opponent || currentMatch?.opponent || "Opponent";
  const matchDate = latestSelection.matchDate || currentMatch?.date || "No date";
  const venue = currentMatch?.venue || "No venue";
  const matchType = currentMatch?.type || "match";

  teamSheetTitle.textContent = `${teamName} vs ${opponent}`;
  teamSheetMeta.textContent = `${matchDate} • ${venue} • ${matchType}`;

  renderPlayerList(
    startingTeamSheet,
    latestSelection.startingSquad || [],
    "No starting players selected.",
    1
  );

  renderPlayerList(
    benchTeamSheet,
    latestSelection.benchSquad || [],
    "No bench players selected.",
    16
  );

  teamSheetNotes.textContent =
    latestSelection.selectionNotes || "No selection notes added.";
}

function getTeamSheetRole(player, index, fallbackStartNumber) {
  if (player.selectedRole) return player.selectedRole;
  if (player.position) return player.position;

  const defaultRoles = {
    1: "Loosehead Prop",
    2: "Hooker",
    3: "Tighthead Prop",
    4: "Lock",
    5: "Lock",
    6: "Flanker",
    7: "Flanker",
    8: "Number Eight",
    9: "Scrumhalf",
    10: "Flyhalf",
    11: "Wing",
    12: "Inside Centre",
    13: "Outside Centre",
    14: "Wing",
    15: "Fullback",
    16: "Loosehead Prop",
    17: "Hooker",
    18: "Tighthead Prop",
    19: "Lock",
    20: "Flanker",
    21: "Scrumhalf",
    22: "Flyhalf / Centre",
    23: "Outside Back"
  };

  const number = index + fallbackStartNumber;

  return defaultRoles[number] || "No position";
}

function renderPlayerList(container, players, emptyMessage, fallbackStartNumber) {
  container.innerHTML = "";

  if (!players.length) {
    container.innerHTML = `
      <div class="list-item">
        ${emptyMessage}
      </div>
    `;

    return;
  }

  players.forEach((player, index) => {
    const number = index + fallbackStartNumber;
    const selectedRole = getTeamSheetRole(player, index, fallbackStartNumber);

    const item = document.createElement("div");
    item.className = "team-sheet-player elite-card";

    item.innerHTML = `
      <div class="team-sheet-number">
        ${number}
      </div>

      <div class="team-sheet-info">
        <h3>${player.name || "Unknown Player"}</h3>
        <p>${selectedRole}</p>

        ${
          player.position && player.position !== selectedRole
            ? `<small class="small-text">Profile position: ${player.position}</small>`
            : `<small class="small-text">Match-day role confirmed</small>`
        }
      </div>
    `;

    container.appendChild(item);
  });
}

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

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

  if (!matchId) {
    teamSheetTitle.textContent = "Invalid Match";
    teamSheetMeta.textContent = "No match ID was provided.";
    hideLoader();
    return;
  }

  showLoader("Loading team sheet...");

  try {
    const hasAccess = await loadMatch();

    if (!hasAccess) {
      hideLoader();
      return;
    }

    await loadTeamSheet();
  } catch (error) {
    console.error("Team sheet error:", error);

    teamSheetTitle.textContent = "Could not load team sheet";

    startingTeamSheet.innerHTML = `
      <div class="list-item">
        Error: ${error.message}
      </div>
    `;

    benchTeamSheet.innerHTML = `
      <div class="list-item">
        Bench could not be loaded.
      </div>
    `;

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