import { getSession, logout } from "./api.js";

const MONTH_NAMES = [
  "Ocak",
  "Şubat",
  "Mart",
  "Nisan",
  "Mayıs",
  "Haziran",
  "Temmuz",
  "Ağustos",
  "Eylül",
  "Ekim",
  "Kasım",
  "Aralık"
];

const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const mobilePageNavToggle = document.getElementById("mobilePageNavToggle");
const summaryPageNav = document.getElementById("summaryPageNav");
const summaryMonthSelect = document.getElementById("summaryMonthSelect");
const summaryYearSelect = document.getElementById("summaryYearSelect");
const summaryChartWrap = document.getElementById("summaryChartWrap");
const summaryChartCaption = document.getElementById("summaryChartCaption");
const summaryMetrics = document.getElementById("summaryMetrics");

let mobileNavOpen = false;
let allMonthEntries = [];
let selectedMonth = new Date().getMonth() + 1;
let selectedYear = new Date().getFullYear();

function escapeHtml(value) {
  return String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

async function fetchSummary(month, year) {
  const query = new URLSearchParams({
    month: String(month),
    year: String(year)
  });
  const response = await fetch(`/api/summary.php?${query.toString()}`, {
    credentials: "same-origin"
  });
  const data = await response.json().catch(() => ({}));

  if (!response.ok || data.ok === false) {
    throw new Error(data.message || "Bir istek hatasi olustu.");
  }

  return data;
}

function renderDefaultSelectors() {
  summaryMonthSelect.innerHTML = MONTH_NAMES
    .map((label, index) => `<option value="${index + 1}" ${(index + 1) === selectedMonth ? "selected" : ""}>${label}</option>`)
    .join("");

  const years = [];
  for (let year = selectedYear + 1; year >= Math.max(2000, selectedYear - 10); year -= 1) {
    years.push(year);
  }

  summaryYearSelect.innerHTML = years
    .map((year) => `<option value="${year}" ${year === selectedYear ? "selected" : ""}>${year}</option>`)
    .join("");
}

function renderSelectors(availableMonths, activeMonth, activeYear) {
  allMonthEntries = availableMonths || [];

  if (!allMonthEntries.length) {
    renderDefaultSelectors();
    summaryMonthSelect.value = String(activeMonth);
    summaryYearSelect.value = String(activeYear);
    return;
  }

  const years = [...new Set(allMonthEntries.map((item) => Number(String(item.value).slice(0, 4))))].sort((a, b) => b - a);
  const activeYearMonths = allMonthEntries
    .filter((item) => Number(String(item.value).slice(0, 4)) === activeYear)
    .map((item) => Number(String(item.value).slice(5, 7)));

  summaryYearSelect.innerHTML = years
    .map((year) => `<option value="${year}" ${year === activeYear ? "selected" : ""}>${year}</option>`)
    .join("");

  summaryMonthSelect.innerHTML = activeYearMonths
    .sort((a, b) => a - b)
    .map((month) => `<option value="${month}" ${month === activeMonth ? "selected" : ""}>${MONTH_NAMES[month - 1]}</option>`)
    .join("");

  if (!activeYearMonths.includes(activeMonth) && activeYearMonths.length) {
    summaryMonthSelect.value = String(activeYearMonths[activeYearMonths.length - 1]);
    selectedMonth = Number(summaryMonthSelect.value);
  }
}

function renderMetrics(metrics, selectedLabel) {
  const cards = [
    {
      title: "Toplam Max Hasta Sayısı",
      value: metrics.maxPatientCount ?? 0
    },
    {
      title: "Yaş Ortalaması",
      value: metrics.averageAge == null ? "-" : `${metrics.averageAge}`
    },
    {
      title: "Arşivlenen Hasta Sayısı",
      value: metrics.archivedCount ?? 0
    },
    {
      title: "Eklenen Hasta Sayısı",
      value: metrics.addedCount ?? 0
    },
    {
      title: "Eklenen Order Sayısı",
      value: metrics.orderCount ?? 0
    },
    {
      title: "Eklenen Dosya Sayısı",
      value: metrics.fileCount ?? 0
    }
  ];

  summaryMetrics.innerHTML = cards.map((card) => `
    <article class="summary-metric-card">
      <p class="eyebrow">${escapeHtml(selectedLabel)}</p>
      <h4>${escapeHtml(card.title)}</h4>
      <strong>${escapeHtml(card.value)}</strong>
    </article>
  `).join("");
}

function renderChart(graphMonths, activeValue) {
  const items = Array.isArray(graphMonths) ? graphMonths : [];
  const maxCount = Math.max(...items.map((item) => Number(item.patientCount || 0)), 1);
  const barWidth = 44;
  const gap = 18;
  const chartHeight = 220;
  const chartWidth = Math.max(items.length * (barWidth + gap) + 32, 320);

  const barsMarkup = items.map((item, index) => {
    const count = Number(item.patientCount || 0);
    const barHeight = Math.max(10, Math.round((count / maxCount) * 160));
    const x = 16 + index * (barWidth + gap);
    const y = 180 - barHeight;
    const isActive = item.value === activeValue;

    return `
      <g class="summary-chart-bar-group">
        <rect
          x="${x}"
          y="${y}"
          width="${barWidth}"
          height="${barHeight}"
          rx="14"
          class="summary-chart-bar${isActive ? " is-active" : ""}"
        ></rect>
        <text x="${x + barWidth / 2}" y="${y - 8}" text-anchor="middle" class="summary-chart-value">${count}</text>
        <text x="${x + barWidth / 2}" y="204" text-anchor="middle" class="summary-chart-label">${escapeHtml(item.label)}</text>
      </g>
    `;
  }).join("");

  summaryChartWrap.innerHTML = `
    <div class="summary-chart-scroll">
      <svg viewBox="0 0 ${chartWidth} ${chartHeight}" class="summary-chart-svg" role="img" aria-label="Aylık hasta sayısı grafiği">
        <line x1="12" y1="180" x2="${chartWidth - 12}" y2="180" class="summary-chart-axis"></line>
        ${barsMarkup}
      </svg>
    </div>
  `;
}

function setMobileNavState(isOpen) {
  mobileNavOpen = Boolean(isOpen);
  summaryPageNav?.classList.toggle("page-nav-mobile-open", mobileNavOpen);
  mobilePageNavToggle?.setAttribute("aria-expanded", mobileNavOpen ? "true" : "false");
}

function syncMobileHeader() {
  const isMobile = window.innerWidth <= 860;
  mobilePageNavToggle?.classList.toggle("hidden", !isMobile);

  if (isMobile) {
    summaryPageNav?.classList.toggle("page-nav-mobile-open", mobileNavOpen);
    return;
  }

  summaryPageNav?.classList.remove("page-nav-mobile-open");
  mobilePageNavToggle?.setAttribute("aria-expanded", "false");
  mobileNavOpen = false;
}

async function loadSummary() {
  summaryMetrics.innerHTML = '<p class="empty-state">Yükleniyor...</p>';

  try {
    const data = await fetchSummary(selectedMonth, selectedYear);
    renderSelectors(data.availableMonths || [], data.selectedMonth?.month || selectedMonth, data.selectedMonth?.year || selectedYear);
    renderMetrics(data.metrics || {}, data.selectedMonth?.label || `${MONTH_NAMES[selectedMonth - 1]} ${selectedYear}`);
    renderChart(data.graphMonths || [], `${selectedYear}-${String(selectedMonth).padStart(2, "0")}`);
    summaryChartCaption.textContent = `${data.selectedMonth?.label || ""} seçili. Grafikte her ayın maksimum hasta sayısı gösterilir.`;
  } catch (error) {
    renderDefaultSelectors();
    summaryMonthSelect.value = String(selectedMonth);
    summaryYearSelect.value = String(selectedYear);
    summaryMetrics.innerHTML = `<p class="error-text">${escapeHtml(error.message)}</p>`;
    summaryChartWrap.innerHTML = "";
    summaryChartCaption.textContent = "Veri yüklenemedi.";
  }
}

async function init() {
  const session = await getSession();
  if (!session.authenticated) {
    window.location.replace("index.php");
    return;
  }

  welcomeMessage.textContent = `Hoş geldin ${session.user.username}`;
  renderDefaultSelectors();

  summaryMonthSelect.addEventListener("change", async () => {
    selectedMonth = Number(summaryMonthSelect.value);
    await loadSummary();
  });

  summaryYearSelect.addEventListener("change", async () => {
    selectedYear = Number(summaryYearSelect.value);
    const availableMonthsForYear = allMonthEntries
      .filter((item) => Number(String(item.value).slice(0, 4)) === selectedYear)
      .map((item) => Number(String(item.value).slice(5, 7)))
      .sort((a, b) => a - b);

    if (availableMonthsForYear.length && !availableMonthsForYear.includes(selectedMonth)) {
      selectedMonth = availableMonthsForYear[availableMonthsForYear.length - 1];
    }

    await loadSummary();
  });

  logoutBtn?.addEventListener("click", async () => {
    try {
      await logout();
    } finally {
      window.location.replace("index.php");
    }
  });

  mobilePageNavToggle?.addEventListener("click", () => {
    setMobileNavState(!mobileNavOpen);
  });

  window.addEventListener("resize", syncMobileHeader);
  syncMobileHeader();
  await loadSummary();
}

init();
