import { Document, Packer, Paragraph, type Table } from "docx";
import PDFDocument from "pdfkit";
import { prisma } from "../prisma.js";
import { buildIndicatorKpiPayload } from "./indicatorKpis.js";
import {
  computeFeedbackMetrics,
  derivedStatus,
  PROVIDER_METRIC_HEADERS,
  PROVIDER_METRIC_WIDTHS,
  providerMetricRows,
  resolveFirstStaffReply,
  responseAt,
  timelinessVerdict,
} from "./feedbackMetrics.js";
import { trackedRosterRoleFilter } from "./traineeRoster.js";
import { formatReportDate, loadSystemLogo, REPORT_THEME } from "./reportTheme.js";
import {
  buildDocxBrandingHeader,
  buildDocxGridTable,
  buildDocxKeyValueTable,
  buildDocxSectionHeading,
  PdfReportLayout,
} from "./reportSections.js";

type MetricUnit = "%" | "count";

function metric(v: number, unit: MetricUnit, denominator?: number | null) {
  if (unit === "%" && (denominator ?? 0) <= 0) return "-";
  return unit === "%" ? `${Math.round(v * 10) / 10}%` : String(Math.round(v));
}

export async function buildDashboardExecutiveReportData(projectId: bigint) {
  const [project, providersCount, traineesCount, kpi] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { id: true, projectCode: true, title: true, donor: true, sector: true, location: true } }),
    prisma.trainingProvider.count({ where: { projectId } }),
    prisma.trainee.count({ where: { projectId, rosterRole: trackedRosterRoleFilter() } }),
    buildIndicatorKpiPayload(projectId),
  ]);
  if (!project) return null;
  const indicatorsByCode = new Map(kpi.indicators.map((i) => [i.code, i]));
  const rows = kpi.kpis
    .filter((x) => x.tpId === "PROJECT")
    .map((x) => {
      const ind = indicatorsByCode.get(x.indicatorCode);
      const unit: MetricUnit = ind?.computationMode === "percentage" ? "%" : "count";
      return {
        code: x.indicatorCode,
        name: ind?.name ?? x.indicatorCode,
        claimed: metric(x.claimed, unit, x.claimedDenominator),
        verified: metric(x.verified, unit, x.verifiedDenominator),
        status: ind?.thresholdValue != null && x.verified < Number(ind.thresholdValue) ? "BELOW_THRESHOLD" : "OK",
      };
    })
    .sort((a, b) => a.name.localeCompare(b.name));
  return {
    projectId: project.id.toString(),
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    sector: project.sector ?? "N/A",
    location: project.location ?? "N/A",
    providersCount,
    traineesCount,
    rows,
    generatedAt: new Date().toISOString(),
  };
}

export async function buildProviderProfileReportData(projectId: bigint, providerId: bigint) {
  const [project, provider, trainingsCount, traineesCount, kpi] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.trainingProvider.findFirst({
      where: { id: providerId, projectId },
      select: { id: true, tpCode: true, name: true, contactName: true, contactEmail: true, contactPhone: true },
    }),
    prisma.training.count({ where: { projectId, trainingProviderId: providerId } }),
    prisma.trainee.count({
      where: { projectId, trainingProviderId: providerId, rosterRole: trackedRosterRoleFilter() },
    }),
    buildIndicatorKpiPayload(projectId),
  ]);
  if (!project || !provider) return null;
  const tpId = provider.id.toString();
  const indicatorsByCode = new Map(kpi.indicators.map((i) => [i.code, i]));
  const rows = kpi.kpis
    .filter((x) => x.tpId === tpId)
    .map((x) => {
      const ind = indicatorsByCode.get(x.indicatorCode);
      const unit: MetricUnit = ind?.computationMode === "percentage" ? "%" : "count";
      return {
        name: ind?.name ?? x.indicatorCode,
        claimed: metric(x.claimed, unit, x.claimedDenominator),
        verified: metric(x.verified, unit, x.verifiedDenominator),
      };
    })
    .sort((a, b) => a.name.localeCompare(b.name));
  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    providerCode: provider.tpCode,
    providerName: provider.name,
    contactName: provider.contactName ?? "N/A",
    contactEmail: provider.contactEmail ?? "N/A",
    contactPhone: provider.contactPhone ?? "N/A",
    trainingsCount,
    traineesCount,
    rows,
    generatedAt: new Date().toISOString(),
  };
}

export async function buildTraineeProfileReportData(projectId: bigint, traineeId: bigint) {
  const [project, t] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.trainee.findFirst({
      where: { id: traineeId, projectId },
      include: { trainingProvider: { select: { name: true, tpCode: true } }, training: { select: { title: true } } },
    }),
  ]);
  if (!project || !t) return null;
  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    traineeUniqueId: t.traineeUniqueId,
    externalBeneficiaryId: t.externalBeneficiaryId ?? "N/A",
    fullName: [t.firstName, t.fatherName, t.grandfatherName].filter(Boolean).join(" "),
    sex: t.sex,
    ageYears: t.ageYears != null ? String(t.ageYears) : "N/A",
    phone: t.phonePrimary ?? "N/A",
    email: t.email ?? "N/A",
    region: t.region ?? "N/A",
    subCity: t.subCity ?? "N/A",
    woreda: t.woreda ?? "N/A",
    kebele: t.kebele ?? "N/A",
    provider: `${t.trainingProvider.tpCode} - ${t.trainingProvider.name}`,
    training: t.training?.title ?? "N/A",
    education: t.highestEducation ?? "N/A",
    employmentStatus: t.employmentStatus ?? "N/A",
    inclusion: {
      disability: t.disabilityFlag ? "Yes" : "No",
      idp: t.idpFlag ? "Yes" : "No",
      returnee: t.returneeFlag ? "Yes" : "No",
      lowIncome: t.lowIncomeFlag ? "Yes" : "No",
    },
    generatedAt: new Date().toISOString(),
  };
}

export async function buildIndicatorCatalogueReportData(projectId: bigint, focusCode?: string | null) {
  const [project, kpi] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    buildIndicatorKpiPayload(projectId),
  ]);
  if (!project) return null;
  const indicatorFilter = focusCode?.trim();
  const selectedIndicators = indicatorFilter
    ? kpi.indicators.filter((i) => i.code === indicatorFilter)
    : kpi.indicators;
  const rows = selectedIndicators.map((ind) => {
    const p = kpi.kpis.find((x) => x.indicatorCode === ind.code && x.tpId === "PROJECT");
    const unit: MetricUnit = ind.computationMode === "percentage" ? "%" : "count";
    return {
      name: ind.name,
      code: ind.code,
      claimed: metric(p?.claimed ?? 0, unit, (p as any)?.claimedDenominator ?? 0),
      verified: metric(p?.verified ?? 0, unit, (p as any)?.verifiedDenominator ?? 0),
      status: ind.thresholdValue != null && (p?.verified ?? 0) < Number(ind.thresholdValue) ? "BELOW_THRESHOLD" : "OK",
    };
  });
  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    rows,
    generatedAt: new Date().toISOString(),
  };
}

/**
 * Feedback / GRM summary dataset.
 *
 * Every metric is computed over the FULL register (no row cap) through
 * `computeFeedbackMetrics`, so the exported numbers always match the KPI cards
 * and the grievance indicator. Timeliness comes from the first response date.
 */
export async function buildFeedbackSummaryReportData(projectId: bigint, providerId?: bigint | null) {
  const [project, threads] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.feedbackThread.findMany({
      where: { projectId, ...(providerId ? { trainingProviderId: providerId } : {}) },
      include: {
        trainingProvider: { select: { tpCode: true, name: true } },
        messages: {
          where: { authorType: { in: ["admin", "tp"] } },
          orderBy: { createdAt: "asc" },
          take: 1,
          select: { authorType: true, createdAt: true },
        },
      },
      orderBy: { id: "desc" },
    }),
  ]);
  if (!project) return null;

  const now = new Date();
  const { byProvider, ...summary } = computeFeedbackMetrics(threads, now);

  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    summary,
    byProvider,
    rows: threads.map((t) => {
      const input = {
        dueAt: t.dueAt,
        firstTpResponseAt: t.firstTpResponseAt,
        firstStaffReplyAt: resolveFirstStaffReply(t.messages),
      };
      const respondedAt = responseAt(input);
      return {
        ref: t.refCode,
        category: t.category,
        status: derivedStatus(input),
        subject: t.subject,
        provider: `${t.trainingProvider.tpCode} - ${t.trainingProvider.name}`,
        submittedAt: t.submittedAt.toISOString().slice(0, 10),
        dueAt: t.dueAt.toISOString().slice(0, 10),
        firstResponseAt: respondedAt ? respondedAt.toISOString().slice(0, 10) : "-",
        timely: timelinessVerdict(input, now),
      };
    }),
    generatedAt: new Date().toISOString(),
  };
}

/**
 * Feedback / GRM detailed dataset (full register, no row cap).
 *
 * Rows are grouped by training provider (tpCode, then submission date) so a
 * provider's cases read as one block instead of being scattered. Each row carries
 * the submitter's feedback and the provider's response in separate columns.
 */
export async function buildFeedbackDetailedReportData(projectId: bigint, providerId?: bigint | null) {
  const [project, threads] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.feedbackThread.findMany({
      where: { projectId, ...(providerId ? { trainingProviderId: providerId } : {}) },
      include: {
        trainingProvider: { select: { tpCode: true, name: true } },
        messages: { orderBy: { createdAt: "asc" } },
      },
    }),
  ]);
  if (!project) return null;

  const now = new Date();
  const { byProvider, ...summary } = computeFeedbackMetrics(threads, now);

  // Group per provider: PII must stay redacted for provider-scoped exports.
  const redactPersonalData = providerId !== null && providerId !== undefined;
  const ordered = [...threads].sort((a, b) => {
    const left = `${a.trainingProvider.tpCode}\u0000${a.trainingProvider.name}`;
    const right = `${b.trainingProvider.tpCode}\u0000${b.trainingProvider.name}`;
    if (left !== right) return left < right ? -1 : 1;
    return a.submittedAt.getTime() - b.submittedAt.getTime();
  });

  const rows = ordered.map((t) => {
    const input = {
      dueAt: t.dueAt,
      firstTpResponseAt: t.firstTpResponseAt,
      firstStaffReplyAt: resolveFirstStaffReply(t.messages),
    };
    const respondedAt = responseAt(input);
    const feedbackMessage = t.messages.find((m) => m.authorType === "public")?.body ?? t.description;
    const responseMessage = t.messages
      .filter((m) => m.authorType !== "public")
      .map((m) => m.body.trim())
      .filter(Boolean)
      .join("\n\n");

    return {
      provider: `${t.trainingProvider.tpCode} - ${t.trainingProvider.name}`,
      ref: t.refCode,
      category: t.category,
      status: derivedStatus(input),
      subject: t.subject,
      feedbackMessage,
      responseMessage,
      submitterName: redactPersonalData ? "Confidential" : t.submitterName,
      submitterEmail: redactPersonalData ? "***@***" : t.submitterEmail,
      submitterPhone: redactPersonalData ? "N/A" : t.submitterPhone ?? "N/A",
      region: redactPersonalData ? "N/A" : t.region ?? "N/A",
      submittedAt: t.submittedAt.toISOString().slice(0, 16).replace("T", " "),
      dueAt: t.dueAt.toISOString().slice(0, 16).replace("T", " "),
      firstResponseAt: respondedAt ? respondedAt.toISOString().slice(0, 16).replace("T", " ") : "Not responded",
      timely: timelinessVerdict(input, now),
    };
  });

  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    summary,
    byProvider,
    rows,
    generatedAt: new Date().toISOString(),
  };
}

export async function buildVerificationRunsSummaryReportData(projectId: bigint, providerId?: bigint | null) {
  const [project, runs] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.verificationSampleRun.findMany({
      where: { projectId, ...(providerId ? { trainingProviderId: providerId } : {}) },
      include: {
        trainingProvider: { select: { tpCode: true, name: true } },
        indicator: { select: { code: true, name: true } },
        subjects: { select: { verifiedValue: true } },
      },
      orderBy: [{ drawnAt: "desc" }, { id: "desc" }],
      take: 500,
    }),
  ]);
  if (!project) return null;
  const rows = runs.map((r) => {
    const decided = r.subjects.filter((s) => s.verifiedValue !== null).length;
    const verifiedYes = r.subjects.filter((s) => s.verifiedValue === true).length;
    const confirmRate = decided > 0 ? `${Math.round((verifiedYes / decided) * 1000) / 10}%` : "-";
    return {
      id: r.id.toString(),
      provider: `${r.trainingProvider.tpCode} - ${r.trainingProvider.name}`,
      indicator: r.indicator.name,
      stage: r.stageKey ?? "default",
      period: r.periodKey ?? "N/A",
      status: r.status,
      sampleSize: r.sampleSize,
      decided,
      verifiedYes,
      confirmRate,
      drawnAt: r.drawnAt.toISOString().slice(0, 10),
      finalizedAt: r.finalizedAt ? r.finalizedAt.toISOString().slice(0, 10) : "-",
    };
  });
  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    rows,
    generatedAt: new Date().toISOString(),
  };
}

export async function buildActivitiesComplianceReportData(projectId: bigint, providerId?: bigint | null) {
  const [project, activities, submissions] = await Promise.all([
    prisma.project.findUnique({ where: { id: projectId }, select: { projectCode: true, title: true, donor: true } }),
    prisma.projectActivity.findMany({
      where: { projectId },
      include: { rules: true },
      orderBy: [{ sortOrder: "asc" }, { code: "asc" }],
      take: 500,
    }),
    prisma.tpActivitySubmission.findMany({
      where: { projectId, ...(providerId ? { trainingProviderId: providerId } : {}) },
      include: { trainingProvider: { select: { tpCode: true, name: true } } },
      orderBy: { id: "desc" },
      take: 3000,
    }),
  ]);
  if (!project) return null;
  const grouped = new Map<string, { submitted: number; approved: number; rejected: number; providers: Set<string> }>();
  submissions.forEach((s) => {
    const key = s.projectActivityId.toString();
    const cur = grouped.get(key) ?? { submitted: 0, approved: 0, rejected: 0, providers: new Set<string>() };
    if (s.status !== "submitted" || s.submittedAt) cur.submitted += 1;
    if (s.status === "approved") cur.approved += 1;
    if (s.status === "rejected") cur.rejected += 1;
    cur.providers.add(s.trainingProviderId.toString());
    grouped.set(key, cur);
  });
  const rows = activities.map((a) => {
    const g = grouped.get(a.id.toString()) ?? { submitted: 0, approved: 0, rejected: 0, providers: new Set<string>() };
    const complianceRate = g.submitted > 0 ? Math.round((g.approved / g.submitted) * 1000) / 10 : 0;
    return {
      code: a.code,
      name: a.name,
      scope: a.submissionScope,
      rulesConfigured: a.rules.length,
      submitted: g.submitted,
      approved: g.approved,
      rejected: g.rejected,
      providerCoverage: g.providers.size,
      complianceRate: `${complianceRate}%`,
    };
  });
  return {
    projectCode: project.projectCode,
    projectTitle: project.title,
    donor: project.donor ?? "N/A",
    rows,
    generatedAt: new Date().toISOString(),
  };
}

export type ReportExtraSection = { title: string; headers: string[]; rows: string[][]; widths?: number[] };

export async function buildStandardDocxReport(
  title: string,
  subtitle: string,
  infoRows: Array<[string, string]>,
  tableHeaders: string[],
  tableRows: string[][],
  notes?: string,
  extraSections: ReportExtraSection[] = [],
) {
  const logo = loadSystemLogo();
  const children: Array<Paragraph | Table> = [
    buildDocxBrandingHeader(logo, title, subtitle),
    new Paragraph(""),
    buildDocxSectionHeading("1. Overview"),
    buildDocxKeyValueTable(infoRows, 35),
    new Paragraph(""),
    buildDocxSectionHeading("2. Performance Summary"),
    buildDocxGridTable(tableHeaders, tableRows),
  ];
  let sectionNumber = 2;
  for (const section of extraSections) {
    sectionNumber += 1;
    children.push(new Paragraph(""));
    children.push(buildDocxSectionHeading(`${sectionNumber}. ${section.title}`));
    children.push(buildDocxGridTable(section.headers, section.rows));
  }
  if (notes) {
    sectionNumber += 1;
    children.push(new Paragraph(""));
    children.push(buildDocxSectionHeading(`${sectionNumber}. Notes`));
    children.push(new Paragraph(notes));
  }
  const doc = new Document({
    sections: [
      {
        properties: { page: { margin: { top: 1000, right: 1000, bottom: 1000, left: 1000 } } },
        children,
      },
    ],
  });
  return Buffer.from(await Packer.toBuffer(doc));
}

export async function buildStandardPdfReport(
  title: string,
  subtitle: string,
  infoRows: Array<[string, string]>,
  tableHeaders: string[],
  tableRows: string[][],
  notes?: string,
  extraSections: ReportExtraSection[] = [],
) {
  const doc = new PDFDocument({ size: REPORT_THEME.page.size, margin: REPORT_THEME.page.margin, bufferPages: true });
  const chunks: Buffer[] = [];
  doc.on("data", (c: Buffer) => chunks.push(c));
  const layout = new PdfReportLayout(doc, loadSystemLogo());
  layout.drawHeader(title, subtitle);
  layout.sectionTitle("1. Overview", title, subtitle);
  layout.keyValueTable(infoRows, title, subtitle);
  layout.sectionTitle("2. Performance Summary", title, subtitle);
  layout.gridTable(tableHeaders, tableRows, tableHeaders.map(() => layout.pageWidth / tableHeaders.length), title, subtitle);
  let sectionNumber = 2;
  for (const section of extraSections) {
    sectionNumber += 1;
    layout.sectionTitle(`${sectionNumber}. ${section.title}`, title, subtitle);
    const widths = section.widths?.map((w) => layout.pageWidth * w) ?? section.headers.map(() => layout.pageWidth / section.headers.length);
    layout.gridTable(section.headers, section.rows, widths, title, subtitle);
  }
  if (notes) {
    sectionNumber += 1;
    layout.sectionTitle(`${sectionNumber}. Notes`, title, subtitle);
    doc.fillColor(`#${REPORT_THEME.text}`).font("Helvetica").fontSize(10).text(notes, doc.page.margins.left, layout.cursorY, {
      width: layout.pageWidth,
      align: "justify",
    });
    layout.cursorY += 36;
  }
  layout.drawPageNumbers();
  doc.end();
  return await new Promise<Buffer>((resolve) => doc.on("end", () => resolve(Buffer.concat(chunks))));
}

type FeedbackDetailedReportData = NonNullable<Awaited<ReturnType<typeof buildFeedbackDetailedReportData>>>;

/**
 * Detailed GRM export: overview, a per-provider timeliness table, then the case
 * records grouped so all of one provider's feedback reads as a single block.
 */
export async function buildFeedbackDetailedPdfReport(data: FeedbackDetailedReportData) {
  const title = "Feedback / GRM Detailed Report";
  const subtitle = "PBPS Monitoring and Verification Information System";
  const doc = new PDFDocument({ size: REPORT_THEME.page.size, margin: REPORT_THEME.page.margin, bufferPages: true });
  const chunks: Buffer[] = [];
  doc.on("data", (c: Buffer) => chunks.push(c));
  const layout = new PdfReportLayout(doc, loadSystemLogo());

  layout.drawHeader(title, subtitle);
  layout.sectionTitle("1. Overview", title, subtitle);
  layout.keyValueTable(
    [
      ["Project", `${data.projectCode} - ${data.projectTitle}`],
      ["Donor", data.donor],
      ["Total", String(data.summary.total)],
      ["Responded", String(data.summary.responded)],
      ["  • timely (<= due date)", String(data.summary.timely)],
      ["  • late (after due date)", String(data.summary.late)],
      ["No response (past due)", String(data.summary.overdueUnresponded)],
      ["Pending (inside window)", String(data.summary.pending)],
      ["Timely <=7d", `${data.summary.timelyPct}%`],
      ["Report Date", formatReportDate(data.generatedAt)],
    ],
    title,
    subtitle,
  );

  layout.sectionTitle("2. Provider Timeliness", title, subtitle);
  layout.gridTable(
    PROVIDER_METRIC_HEADERS,
    providerMetricRows(data),
    PROVIDER_METRIC_WIDTHS.map((w) => layout.pageWidth * w),
    title,
    subtitle,
  );

  const detailHeaders = ["Ref", "Category", "Status", "Subject", "Submitted", "First Response", "Timely"];
  const detailWidths = detailHeaders.map(() => layout.pageWidth / detailHeaders.length);
  let sectionNumber = 2;
  const groups = new Map<string, typeof data.rows>();
  for (const row of data.rows) {
    const bucket = groups.get(row.provider) ?? [];
    bucket.push(row);
    groups.set(row.provider, bucket);
  }
  for (const [provider, rows] of groups) {
    sectionNumber += 1;
    layout.sectionTitle(`${sectionNumber}. ${provider}`, title, subtitle);
    layout.gridTable(
      detailHeaders,
      rows.map((r) => [r.ref, r.category, r.status, r.subject, r.submittedAt, r.firstResponseAt, r.timely]),
      detailWidths,
      title,
      subtitle,
    );
  }

  sectionNumber += 1;
  layout.sectionTitle(`${sectionNumber}. Notes`, title, subtitle);
  doc
    .fillColor(`#${REPORT_THEME.text}`)
    .font("Helvetica")
    .fontSize(10)
    .text(
      "Per-row Timely column: Yes = replied on or before the due date (7 days from submission), No = replied late or not replied at all by the due date, " +
        "Pending = due date still in the future. Responded = Timely + Late; Total = Responded + No response + Pending; " +
        "Timely rate = Timely / (Responded + No response). Status is set automatically when a response is sent. " +
        "The full submitter feedback and the provider response text are provided as separate columns in the CSV export.",
      doc.page.margins.left,
      layout.cursorY,
      { width: layout.pageWidth, align: "justify" },
    );
  layout.drawPageNumbers();
  doc.end();
  return await new Promise<Buffer>((resolve) => doc.on("end", () => resolve(Buffer.concat(chunks))));
}

