import { initI18n, onLangChange, t, getLang } from "./i18n";
import { initSidebar } from "./sidebar";
import { projectIndent } from "./project-indent";

interface ChecklistItem {
  labelDE: string;
  labelEN: string;
  noteDE?: string;
  noteEN?: string;
  rule?: string;
}

interface ChecklistGroup {
  titleDE: string;
  titleEN: string;
  items: ChecklistItem[];
}

interface Checklist {
  slug: string;
  titleDE: string;
  titleEN: string;
  descriptionDE: string;
  descriptionEN: string;
  regime: string;
  courtDE: string;
  courtEN: string;
  deadlineDE?: string;
  deadlineEN?: string;
  referenceDE?: string;
  referenceEN?: string;
  groups: ChecklistGroup[];
}

interface ChecklistInstance {
  id: string;
  template_slug: string;
  name: string;
  project_id?: string | null;
  state: Record<string, boolean>;
  created_by: string;
  created_at: string;
  updated_at: string;
  project_reference?: string | null;
  project_title?: string | null;
}

interface AkteSummary {
  id: string;
  reference?: string | null;
  title: string;
  path: string;
}

let template: Checklist | null = null;
let instances: ChecklistInstance[] = [];
let projects: AkteSummary[] = [];
let totalItems = 0;

function esc(s: string): string {
  const d = document.createElement("div");
  d.textContent = s;
  return d.innerHTML;
}

function templateSlug(): string {
  // /checklisten/{slug}
  const parts = window.location.pathname.split("/").filter(Boolean);
  return parts[1] ?? "";
}

async function loadTemplate() {
  const slug = templateSlug();
  const resp = await fetch(`/api/checklists/${encodeURIComponent(slug)}`);
  if (!resp.ok) {
    document.title = "404 — Paliad";
    document.getElementById("checklist-title")!.textContent = t("checklisten.notfound");
    return;
  }
  template = await resp.json();
  if (template) {
    totalItems = template.groups.reduce((n, g) => n + g.items.length, 0);
  }
  renderHeader();
}

async function loadInstances() {
  const slug = templateSlug();
  try {
    const resp = await fetch(`/api/checklists/${encodeURIComponent(slug)}/instances`);
    if (!resp.ok) {
      instances = [];
    } else {
      instances = await resp.json();
    }
  } catch {
    instances = [];
  }
  renderInstances();
}

async function loadAkten() {
  try {
    const resp = await fetch("/api/projects");
    if (resp.ok) projects = await resp.json();
  } catch {
    projects = [];
  }
  renderAkteOptions();
}

function renderHeader() {
  if (!template) return;
  const isEN = getLang() === "en";
  const title = isEN ? template.titleEN : template.titleDE;
  const desc = isEN ? template.descriptionEN : template.descriptionDE;
  const court = isEN ? template.courtEN : template.courtDE;
  const deadline = isEN ? template.deadlineEN : template.deadlineDE;
  const reference = isEN ? template.referenceEN : template.referenceDE;

  document.title = `${title} — Paliad`;
  document.getElementById("checklist-title")!.textContent = title;
  document.getElementById("checklist-subtitle")!.textContent = desc;

  const courtLabel = isEN ? "Court / Authority" : "Gericht / Behörde";
  const deadlineLabel = isEN ? "Deadline" : "Deadline";
  const refLabel = isEN ? "Reference" : "Rechtsgrundlage";
  const regimeLabel = isEN ? "Regime" : "Bereich";
  const itemsLabel = isEN ? "Items" : "Punkte";

  const parts: string[] = [];
  parts.push(`<div class="checklist-meta-item"><dt>${regimeLabel}</dt><dd><span class="checklist-regime checklist-regime-${esc(template.regime)}">${esc(template.regime)}</span></dd></div>`);
  parts.push(`<div class="checklist-meta-item"><dt>${courtLabel}</dt><dd>${esc(court)}</dd></div>`);
  if (deadline) {
    parts.push(`<div class="checklist-meta-item"><dt>${deadlineLabel}</dt><dd>${esc(deadline)}</dd></div>`);
  }
  if (reference) {
    parts.push(`<div class="checklist-meta-item"><dt>${refLabel}</dt><dd>${esc(reference)}</dd></div>`);
  }
  parts.push(`<div class="checklist-meta-item"><dt>${itemsLabel}</dt><dd>${totalItems}</dd></div>`);
  document.getElementById("checklist-meta")!.innerHTML = parts.join("");
}

function progress(inst: ChecklistInstance): { done: number; pct: number } {
  const done = Object.values(inst.state || {}).filter(Boolean).length;
  const pct = totalItems === 0 ? 0 : Math.round((done / totalItems) * 100);
  return { done, pct };
}

function formatDate(iso: string): string {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return "";
  const lang = getLang();
  return d.toLocaleDateString(lang === "en" ? "en-GB" : "de-DE", {
    year: "numeric", month: "2-digit", day: "2-digit",
  });
}

function renderInstances() {
  const loading = document.getElementById("instances-loading")!;
  const empty = document.getElementById("instances-empty")!;
  const wrap = document.getElementById("instances-tablewrap")!;
  const body = document.getElementById("instances-body")!;

  loading.style.display = "none";

  if (instances.length === 0) {
    empty.style.display = "";
    wrap.style.display = "none";
    return;
  }
  empty.style.display = "none";
  wrap.style.display = "";

  const isEN = getLang() === "en";
  const deleteLabel = isEN ? "Delete" : "Löschen";
  const openLabel = isEN ? "Öffnen" : "Öffnen";
  const personalLabel = isEN ? "personal" : "persönlich";

  body.innerHTML = instances.map((inst) => {
    const { done, pct } = progress(inst);
    const akteCell = inst.project_id && inst.project_reference
      ? `<a href="/projects/${esc(inst.project_id)}" class="checklist-instance-project-link">${esc(inst.project_reference)}</a>`
      : `<span class="entity-muted">${personalLabel}</span>`;
    return `<tr data-id="${esc(inst.id)}" class="checklist-instance-row">
      <td><a href="/checklists/instances/${esc(inst.id)}" class="checklist-instance-name">${esc(inst.name)}</a></td>
      <td>
        <div class="checklist-progress-inline">
          <div class="checklist-progress-bar">
            <div class="checklist-progress-fill" style="width:${pct}%"></div>
          </div>
          <span class="checklist-progress-label">${done} / ${totalItems}</span>
        </div>
      </td>
      <td>${akteCell}</td>
      <td>${esc(formatDate(inst.created_at))}</td>
      <td class="checklist-instance-actions">
        <a class="btn-small btn-ghost" href="/checklists/instances/${esc(inst.id)}">${esc(openLabel)}</a>
        <button type="button" class="btn-small btn-ghost btn-delete-instance" data-id="${esc(inst.id)}" data-name="${esc(inst.name)}">${esc(deleteLabel)}</button>
      </td>
    </tr>`;
  }).join("");

  body.querySelectorAll<HTMLButtonElement>(".btn-delete-instance").forEach((btn) => {
    btn.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      const id = btn.dataset.id!;
      const name = btn.dataset.name ?? "";
      const msg = (t("checklisten.instances.delete.confirm") || "").replace("{name}", name);
      if (!confirm(msg)) return;
      void deleteInstance(id);
    });
  });

  body.querySelectorAll<HTMLTableRowElement>(".checklist-instance-row").forEach((row) => {
    const id = row.dataset.id!;
    row.addEventListener("click", (e) => {
      const target = e.target as HTMLElement;
      if (target.closest("a") || target.closest("button")) return;
      window.location.href = `/checklists/instances/${id}`;
    });
  });
}

function renderAkteOptions() {
  const sel = document.getElementById("new-instance-project") as HTMLSelectElement;
  if (!sel) return;
  const none = sel.querySelector('option[value=""]');
  sel.innerHTML = "";
  if (none) sel.appendChild(none);
  projects.forEach((a) => {
    const opt = document.createElement("option");
    opt.value = a.id;
    opt.textContent = `${projectIndent(a.path)}${a.reference || ""} — ${a.title}`;
    sel.appendChild(opt);
  });
}

function initNewInstance() {
  const modal = document.getElementById("new-instance-modal")!;
  const form = document.getElementById("new-instance-form")! as HTMLFormElement;
  const msg = document.getElementById("new-instance-msg")!;
  const nameInput = document.getElementById("new-instance-name") as HTMLInputElement;
  const akteSel = document.getElementById("new-instance-project") as HTMLSelectElement;

  const open = () => {
    msg.textContent = "";
    msg.className = "form-msg";
    nameInput.value = "";
    akteSel.value = "";
    modal.style.display = "flex";
    nameInput.focus();
  };
  const close = () => { modal.style.display = "none"; };

  document.getElementById("btn-new-instance")!.addEventListener("click", open);
  document.getElementById("new-instance-close")!.addEventListener("click", close);
  document.getElementById("new-instance-cancel")!.addEventListener("click", close);
  modal.addEventListener("click", (e) => { if (e.target === e.currentTarget) close(); });

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const name = nameInput.value.trim();
    if (!name) {
      msg.textContent = t("checklisten.newInstance.error.name");
      msg.className = "form-msg form-msg-error";
      return;
    }
    const akteID = akteSel.value || null;
    const payload: { name: string; project_id?: string } = { name };
    if (akteID) payload.project_id = akteID;

    const slug = templateSlug();
    const submitBtn = form.querySelector(".btn-primary") as HTMLButtonElement;
    submitBtn.disabled = true;
    try {
      const resp = await fetch(`/api/checklists/${encodeURIComponent(slug)}/instances`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!resp.ok) {
        msg.textContent = t("checklisten.newInstance.error.generic");
        msg.className = "form-msg form-msg-error";
        return;
      }
      const created = await resp.json() as ChecklistInstance;
      window.location.href = `/checklists/instances/${encodeURIComponent(created.id)}`;
    } catch {
      msg.textContent = t("checklisten.newInstance.error.generic");
      msg.className = "form-msg form-msg-error";
    } finally {
      submitBtn.disabled = false;
    }
  });
}

async function deleteInstance(id: string) {
  try {
    const resp = await fetch(`/api/checklist-instances/${encodeURIComponent(id)}`, { method: "DELETE" });
    if (!resp.ok && resp.status !== 204) {
      alert(t("checklisten.instances.delete.error"));
      return;
    }
    instances = instances.filter((i) => i.id !== id);
    renderInstances();
  } catch {
    alert(t("checklisten.instances.delete.error"));
  }
}

function initFeedback() {
  const modal = document.getElementById("feedback-modal")!;
  const form = document.getElementById("feedback-form")!;
  const msg = document.getElementById("feedback-msg")!;

  document.getElementById("btn-feedback")!.addEventListener("click", () => {
    msg.textContent = "";
    msg.className = "form-msg";
    modal.style.display = "flex";
  });

  document.getElementById("modal-close")!.addEventListener("click", () => { modal.style.display = "none"; });
  document.getElementById("modal-cancel")!.addEventListener("click", () => { modal.style.display = "none"; });
  modal.addEventListener("click", (e) => { if (e.target === e.currentTarget) modal.style.display = "none"; });

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    if (!template) return;
    const submitBtn = form.querySelector(".btn-submit") as HTMLButtonElement;
    const payload = {
      feedback_type: (document.getElementById("feedback-type") as HTMLSelectElement).value,
      checklist: template.slug,
      message: (document.getElementById("feedback-message") as HTMLTextAreaElement).value.trim(),
    };

    if (!payload.message) {
      msg.textContent = t("checklisten.feedback.error.required");
      msg.className = "form-msg form-msg-error";
      return;
    }

    submitBtn.disabled = true;
    try {
      const resp = await fetch("/api/checklists/feedback", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!resp.ok) {
        msg.textContent = t("checklisten.feedback.error.generic");
        msg.className = "form-msg form-msg-error";
        return;
      }
      msg.textContent = t("checklisten.feedback.success");
      msg.className = "form-msg form-msg-success";
      (document.getElementById("feedback-message") as HTMLTextAreaElement).value = "";
      setTimeout(() => { modal.style.display = "none"; }, 1500);
    } catch {
      msg.textContent = t("checklisten.feedback.error.generic");
      msg.className = "form-msg form-msg-error";
    } finally {
      submitBtn.disabled = false;
    }
  });
}

function rerenderAll() {
  renderHeader();
  renderInstances();
}

document.addEventListener("DOMContentLoaded", () => {
  initI18n();
  initSidebar();
  initNewInstance();
  initFeedback();
  onLangChange(rerenderAll);
  void loadTemplate();
  void loadInstances();
  void loadAkten();
});
