const pdfInput = document.querySelector("#pdfInput");
const excelInput = document.querySelector("#excelInput");
const pdfName = document.querySelector("#pdfName");
const excelName = document.querySelector("#excelName");
const processBtn = document.querySelector("#processBtn");
const runStatus = document.querySelector("#runStatus");
const diffCount = document.querySelector("#diffCount");
const addRowBtn = document.querySelector("#addRowBtn");
const markReviewedBtn = document.querySelector("#markReviewedBtn");
const markAllReviewedBtn = document.querySelector("#markAllReviewedBtn");
const exportBtn = document.querySelector("#exportBtn");
const searchInput = document.querySelector("#searchInput");
const viewSelect = document.querySelector("#viewSelect");
const workGrid = document.querySelector("#workGrid");
const workspace = document.querySelector("#workspace");

const demoRows = [
  {
    fecha: "01/06/2026",
    legajo: "10074",
    empleado: "VARAS PEDRO",
    condicion: "A",
    entradaPdf: "05:30",
    salidaPdf: "14:00",
    horasPdf: "8,50",
    entradaObra: "06:00",
    salidaObra: "14:00",
    horasObra: "8,00",
    tipoHora: "Normal",
    observaciones: "Entrada tomada desde reloj.",
    estado: "Revisar entrada",
    estadoTipo: "warn",
    visado: false
  },
  {
    fecha: "01/06/2026",
    legajo: "4507",
    empleado: "GUTIERREZ ESTEBAN EMMANUEL",
    condicion: "A",
    entradaPdf: "06:58",
    salidaPdf: "",
    horasPdf: "",
    entradaObra: "",
    salidaObra: "",
    horasObra: "",
    tipoHora: "Normal",
    observaciones: "Falta salida en reloj.",
    estado: "Fichada incompleta",
    estadoTipo: "danger",
    visado: false
  },
  {
    fecha: "01/06/2026",
    legajo: "10015",
    empleado: "COTTO LEONARDO",
    condicion: "A",
    entradaPdf: "05:46",
    salidaPdf: "14:00",
    horasPdf: "8,23",
    entradaObra: "06:00",
    salidaObra: "14:00",
    horasObra: "8,00",
    tipoHora: "Normal",
    observaciones: "Validar tolerancia.",
    estado: "Diferencia menor",
    estadoTipo: "ok",
    visado: true
  }
];

function formatFile(input, fallback) {
  const file = input.files && input.files[0];
  if (!file) return fallback;
  const sizeKb = Math.max(1, Math.round(file.size / 1024));
  return `${file.name} - ${sizeKb} KB`;
}

function refreshStatus() {
  const hasPdf = Boolean(pdfInput.files && pdfInput.files.length);
  const hasExcel = Boolean(excelInput.files && excelInput.files.length);

  if (hasPdf && hasExcel) {
    runStatus.textContent = "Listo para comparar";
    return;
  }

  if (hasPdf) {
    runStatus.textContent = "PDF cargado";
    return;
  }

  if (hasExcel) {
    runStatus.textContent = "Excel cargado";
    return;
  }

  runStatus.textContent = "Esperando archivos";
}

pdfInput.addEventListener("change", () => {
  pdfName.textContent = formatFile(pdfInput, "Sin archivo cargado");
  refreshStatus();
});

excelInput.addEventListener("change", () => {
  excelName.textContent = formatFile(excelInput, "Sin archivo cargado");
  refreshStatus();
});

function cell(value = "", editable = true) {
  const safeValue = String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
  return `<td${editable ? ' contenteditable="true"' : ""}>${safeValue}</td>`;
}

function renderRows(rows) {
  const tbody = workGrid.querySelector("tbody");
  tbody.innerHTML = rows.map((row) => `
    <tr>
      <td class="sticky-col"><input type="checkbox"></td>
      ${cell(row.fecha, false)}
      ${cell(row.legajo)}
      ${cell(row.empleado)}
      ${cell(row.condicion)}
      ${cell(row.entradaPdf)}
      ${cell(row.salidaPdf)}
      ${cell(row.horasPdf)}
      ${cell(row.entradaObra)}
      ${cell(row.salidaObra)}
      ${cell(row.horasObra)}
      ${cell(row.tipoHora)}
      ${cell(row.observaciones)}
      <td><span class="pill ${row.estadoTipo || "warn"}">${String(row.estado || "Revisar")
        .replaceAll("&", "&amp;")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")}</span></td>
      <td><input type="checkbox" ${row.visado ? "checked" : ""}></td>
      <td><button class="row-action delete-row" type="button">Eliminar</button></td>
    </tr>
  `).join("");
}

function updateMetrics(summary = {}) {
  document.querySelector("#pdfCount").textContent = summary.pdfCount ?? "0";
  document.querySelector("#okCount").textContent = summary.okCount ?? "0";
  document.querySelector("#reviewCount").textContent = summary.reviewCount ?? "0";
  diffCount.textContent = summary.diffCount ?? "0";
}

async function processFiles() {
  if (window.location.protocol === "file:") {
    return {
      rows: demoRows,
      summary: { pdfCount: 94, okCount: 79, reviewCount: 15, diffCount: 3 },
      demo: true
    };
  }

  const formData = new FormData();
  if (pdfInput.files[0]) formData.append("pdf", pdfInput.files[0]);
  if (excelInput.files[0]) formData.append("excel", excelInput.files[0]);

  const response = await fetch("api/process.php", {
    method: "POST",
    body: formData
  });

  const result = await response.json().catch(() => null);
  if (!response.ok) {
    throw new Error(result?.error || "No se pudo procesar la carga.");
  }

  if (result?.ok === false) {
    throw new Error(result.error || "No se pudo procesar la carga.");
  }

  return result;
}

processBtn.addEventListener("click", async () => {
  workspace.hidden = false;
  runStatus.textContent = "Procesando...";

  try {
    const result = await processFiles();
    renderRows(result.rows || []);
    updateMetrics(result.summary || {});
    runStatus.textContent = result.demo ? "Demo local cargada" : "Procesado";
    applyFilters();
  } catch (error) {
    runStatus.textContent = "Error al procesar";
    diffCount.textContent = "Error";
    alert(error.message);
    console.error(error);
  }
});

addRowBtn.addEventListener("click", () => {
  const tbody = workGrid.querySelector("tbody");
  const row = document.createElement("tr");
  row.innerHTML = `
    <td class="sticky-col"><input type="checkbox"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true"></td>
    <td contenteditable="true">Normal</td>
    <td contenteditable="true"></td>
    <td><span class="pill warn">Manual</span></td>
    <td><input type="checkbox"></td>
    <td><button class="row-action delete-row" type="button">Eliminar</button></td>
  `;
  tbody.appendChild(row);
  row.querySelector("[contenteditable='true']").focus();
  applyFilters();
});

function markRowReviewed(row) {
  const reviewed = row.querySelector("td:nth-last-child(2) input[type='checkbox']");
  const status = row.querySelector(".pill");
  if (!reviewed || !status) return false;

  reviewed.checked = true;
  status.className = "pill ok";
  status.textContent = "Revisado";
  return true;
}

markReviewedBtn.addEventListener("click", () => {
  const selectedRows = Array.from(workGrid.querySelectorAll("tbody .sticky-col input:checked"))
    .map((checkbox) => checkbox.closest("tr"))
    .filter(Boolean);

  if (selectedRows.length === 0) {
    alert("Primero tilda uno o mas renglones en la columna Sel.");
    return;
  }

  selectedRows.forEach(markRowReviewed);
  applyFilters();
});

markAllReviewedBtn.addEventListener("click", () => {
  const rows = Array.from(workGrid.querySelectorAll("tbody tr"));
  if (rows.length === 0) {
    alert("No hay renglones para visar.");
    return;
  }

  rows.forEach(markRowReviewed);
  applyFilters();
});

function rowMatchesView(row) {
  const view = viewSelect.value;
  const status = row.querySelector(".pill")?.textContent.toLowerCase() || "";

  if (view === "Todos los registros") return true;
  if (view === "Incompletos") return status.includes("incompleta");
  if (view === "Solo diferencias") {
    return status.includes("revisar") || status.includes("incompleta") || status.includes("diferencia");
  }

  return true;
}

function applyFilters() {
  const term = searchInput.value.trim().toLowerCase();
  workGrid.querySelectorAll("tbody tr").forEach((row) => {
    const matchesSearch = term.length === 0 || row.textContent.toLowerCase().includes(term);
    row.hidden = !matchesSearch || !rowMatchesView(row);
  });
}

function getCellText(cell) {
  const checkbox = cell.querySelector("input[type='checkbox']");
  if (checkbox) return checkbox.checked ? "SI" : "NO";
  return cell.textContent.trim();
}

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

function buildExcelTable() {
  const headers = Array.from(workGrid.querySelectorAll("thead th"))
    .slice(1, -1)
    .map((header) => `<th>${escapeExcelValue(header.textContent.trim())}</th>`)
    .join("");

  const body = Array.from(workGrid.querySelectorAll("tbody tr"))
    .map((row) => {
      const cells = Array.from(row.children)
        .slice(1, -1)
        .map((cell) => `<td>${escapeExcelValue(getCellText(cell))}</td>`)
        .join("");
      return `<tr>${cells}</tr>`;
    })
    .join("");

  return `
    <html>
      <head>
        <meta charset="utf-8">
        <style>
          table { border-collapse: collapse; font-family: Arial, sans-serif; font-size: 12px; }
          th, td { border: 1px solid #999; padding: 6px; mso-number-format:"\\@"; }
          th { font-weight: bold; background: #eaf1fb; }
        </style>
      </head>
      <body>
        <table>
          <thead><tr>${headers}</tr></thead>
          <tbody>${body}</tbody>
        </table>
      </body>
    </html>
  `;
}

function exportReviewedExcel() {
  const rows = Array.from(workGrid.querySelectorAll("tbody tr"));
  if (rows.length === 0) {
    alert("No hay datos para exportar.");
    return;
  }

  const pendingRows = rows.filter((row) => {
    const reviewed = row.querySelector("td:nth-last-child(2) input");
    return !reviewed?.checked;
  });

  if (pendingRows.length > 0) {
    alert(`Hay ${pendingRows.length} fila(s) sin visar. Revisalas antes de exportar el Excel final.`);
    return;
  }

  const blob = new Blob(["\ufeff", buildExcelTable()], {
    type: "application/vnd.ms-excel;charset=utf-8"
  });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  const today = new Date().toISOString().slice(0, 10);
  link.href = url;
  link.download = `dominion-parte-revisado-${today}.xls`;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
  runStatus.textContent = "Excel final exportado";
}

workGrid.addEventListener("click", (event) => {
  const button = event.target.closest(".delete-row");
  if (!button) return;

  button.closest("tr").remove();
  applyFilters();
});

exportBtn.addEventListener("click", exportReviewedExcel);
searchInput.addEventListener("input", applyFilters);
viewSelect.addEventListener("change", applyFilters);
applyFilters();
