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

const teamForm = document.getElementById("teamForm");
const teamList = document.getElementById("teamList");
const teamFormTitle = document.getElementById("teamFormTitle");

const teamNameInput = document.getElementById("teamName");
const ageGroupInput = document.getElementById("ageGroup");
const cancelTeamEditBtn = document.getElementById("cancelTeamEditBtn");

let activeProfile = null;
let usersCache = [];
let teamsCache = [];
let editingTeamId = null;

const submitButton = teamForm?.querySelector("button[type='submit']");

async function loadPageData() {
  if (!activeProfile?.organisationId) {
    throw new Error("No organisation linked to this user.");
  }
  
  const usersQuery = query(
    collection(db, "users"),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const teamsQuery = query(
    collection(db, "teams"),
    where("organisationId", "==", activeProfile.organisationId),
    orderBy("createdAt", "desc")
  );

  const [usersSnapshot, teamsSnapshot] = await Promise.all([
    getDocs(usersQuery),
    getDocs(teamsQuery)
  ]);

  usersCache = usersSnapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));

  teamsCache = teamsSnapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));
}

function getAssignedStaffNames(team) {
  const assignedIds = team.assignedCoachIds || [];

  if (!assignedIds.length) {
    return "No staff assigned";
  }

  return assignedIds
    .map((userId) => {
      const user = usersCache.find((item) => item.uid === userId);

      if (!user) return "Unknown Staff";

      return `${user.fullName || user.email || "Staff Member"} (${user.role || "role"})`;
    })
    .join(", ");
}

function resetFormMode() {
  editingTeamId = null;

  if (teamForm) {
    teamForm.reset();
  }

  if (teamFormTitle) {
    teamFormTitle.textContent = "Add Team";
  }

  if (submitButton) {
    submitButton.textContent = "Add Team";
    submitButton.disabled = false;
  }

  if (cancelTeamEditBtn) {
    cancelTeamEditBtn.classList.add("hidden");
  }
}

function renderTeams() {
  teamList.innerHTML = "";

  if (!teamsCache.length) {
    teamList.innerHTML = `
      <div class="app-card">
        No teams added yet.
      </div>
    `;
    return;
  }

  teamsCache.forEach((team) => {
    const item = document.createElement("div");
    item.className = "app-card team-card";

    item.innerHTML = `
      <div class="team-card-header">
        <div>
          <span class="section-eyebrow">Rugby Team</span>

          <h3>
            ${team.name || "Unnamed Team"}
            <span>${team.ageGroup || "No age group"}</span>
          </h3>

          <p>
            ${getAssignedStaffNames(team)}
          </p>
        </div>

        <div class="elite-match-score">
          <strong>${team.ageGroup || "U?"}</strong>
        </div>
      </div>

      <div class="elite-match-meta-grid">
        <div>
          <span>Sport</span>
          <strong>${team.sport || "rugby"}</strong>
        </div>

        <div>
          <span>Age Group</span>
          <strong>${team.ageGroup || "Not set"}</strong>
        </div>

        <div>
          <span>Staff</span>
          <strong>${(team.assignedCoachIds || []).length}</strong>
        </div>
      </div>

      <div class="team-card-footer">
        <span class="elite-injury-meta">
          Team ID: ${team.id}
        </span>

        <div class="record-actions">
          <a href="team-performance.html?id=${team.id}" class="btn-primary">
            Performance
          </a>

          <button class="btn-secondary edit-team-btn" data-id="${team.id}" type="button">
            Edit
          </button>

          <button class="btn-danger delete-team-btn" data-id="${team.id}" type="button">
            Delete
          </button>
        </div>
      </div>
    `;

    teamList.appendChild(item);
  });
}

async function teamHasLinkedRecords(teamId) {
  if (!activeProfile?.organisationId) {
    throw new Error("No organisation linked to this user.");
  }
  
  const playersQuery = query(
    collection(db, "players"),
    where("teamId", "==", teamId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const matchesQuery = query(
    collection(db, "matches"),
    where("teamId", "==", teamId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const [playersSnapshot, matchesSnapshot] = await Promise.all([
    getDocs(playersQuery),
    getDocs(matchesQuery)
  ]);

  return !playersSnapshot.empty || !matchesSnapshot.empty;
}

async function canCreateAnotherTeam() {
  if (!activeProfile?.organisationId) return false;

  const organisationRef = doc(db, "organisations", activeProfile.organisationId);
  const organisationSnap = await getDoc(organisationRef);

  if (!organisationSnap.exists()) {
    showToast("Organisation not found.", "error");
    return false;
  }

  const organisation = organisationSnap.data();
  const subscription = organisation.subscription || {};
  const limits = subscription.limits || {};

  const maxTeams = Number(limits.maxTeams || 0);

  if (!maxTeams) {
    showToast("No team limit found for this subscription.", "warning");
    return false;
  }

  if (teamsCache.length >= maxTeams) {
    showToast(
      `Your current subscription allows a maximum of ${maxTeams} team(s). Please upgrade your plan to add more teams.`,
      "warning"
    );

    return false;
  }

  return true;
}

teamForm.addEventListener("submit", async function (event) {
  event.preventDefault();

  if (!activeProfile) {
    showToast("User profile not loaded yet.", "warning");
    return;
  }

  const teamName = teamNameInput.value.trim();
  const ageGroup = ageGroupInput.value.trim();

  if (!teamName) {
    showToast("Please enter a team name.", "warning");
    return;
  }

  if (!ageGroup) {
    showToast("Please enter an age group.", "warning");
    return;
  }
  
  submitButton.disabled = true;
  submitButton.textContent = editingTeamId ? "Updating..." : "Saving...";

  const teamData = {
    name: teamName,
    ageGroup,
    sport: "rugby",
    organisationId: activeProfile.organisationId,
    updatedAt: serverTimestamp()
  };

  try {
    if (!editingTeamId) {
      const allowedToCreateTeam = await canCreateAnotherTeam();

      if (!allowedToCreateTeam) {
        submitButton.disabled = false;
        submitButton.textContent = "Add Team";
        return;
      }
    }

    if (editingTeamId) {
      await updateDoc(doc(db, "teams", editingTeamId), teamData);

      teamsCache = teamsCache.map((team) =>
        team.id === editingTeamId
          ? {
              ...team,
              ...teamData,
              updatedAt: new Date()
            }
          : team
      );

      showToast("Team updated successfully.", "success");
    } else {
      const teamRef = await addDoc(collection(db, "teams"), {
        ...teamData,
        assignedCoachIds: [],
        createdBy: activeProfile.uid,
        createdAt: serverTimestamp()
      });

      teamsCache.unshift({
        id: teamRef.id,
        ...teamData,
        assignedCoachIds: [],
        createdBy: activeProfile.uid,
        createdAt: new Date()
      });

      showToast("Team added successfully.", "success");
    }

    resetFormMode();
    renderTeams();
  } catch (error) {
    console.error("Error saving team:", error);
    showToast("Could not save team: " + error.message, "error");
  }
});

teamList.addEventListener("click", async function (event) {
  const editBtn = event.target.closest(".edit-team-btn");
  const deleteBtn = event.target.closest(".delete-team-btn");

  if (editBtn) {
    const selectedTeamId = editBtn.dataset.id;
    const team = teamsCache.find((item) => item.id === selectedTeamId);

    if (!team) return;

    editingTeamId = team.id;

    teamNameInput.value = team.name || "";
    ageGroupInput.value = team.ageGroup || "";

    teamFormTitle.textContent = "Edit Team";
    submitButton.textContent = "Update Team";
    cancelTeamEditBtn.classList.remove("hidden");

    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  if (deleteBtn) {
    const selectedTeamId = deleteBtn.dataset.id;

    const confirmed = confirm("Are you sure you want to delete this team?");
    if (!confirmed) return;

    try {
      const hasLinkedRecords = await teamHasLinkedRecords(selectedTeamId);

      if (hasLinkedRecords) {
        showToast(
          "This team cannot be deleted because it has players or matches linked to it.",
          "warning"
        );

        return;
      }

      await deleteDoc(doc(db, "teams", selectedTeamId));

      teamsCache = teamsCache.filter((team) => team.id !== selectedTeamId);

      renderTeams();
      showToast("Team deleted.", "success");
    } catch (error) {
      console.error("Error deleting team:", error);
      showToast("Could not delete team: " + error.message, "error");
    }
  }
});

cancelTeamEditBtn.addEventListener("click", function () {
  resetFormMode();
});

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

  showLoader("Loading teams...");

  teamList.innerHTML = `
    <div class="app-card">
      Loading teams...
    </div>
  `;

  try {
    await loadPageData();
    renderTeams();
  } catch (error) {
    console.error("Error saving team:", error);
    showToast("Could not load teams: " + error.message, "error");
  } finally {
    hideLoader();

    if (submitButton) {
      submitButton.disabled = false;
      submitButton.textContent = editingTeamId ? "Update Team" : "Add Team";
    }
  }
});