"use client";

import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { exportChartToXlsx } from "@/app/(main)/chart/_components/exportChartToXlsx";

export interface ShopOrderReplenishmentReportRow {
  shopNo?: string;
  shopName?: string;
  shopOrderDate?: string;
  shopOrderNo?: string;
  itemNo?: string;
  itemName?: string;
  firstOrderQty?: number | string;
  firstOrderActualPickQty?: number | string;
  reorderQty?: number | string;
  reorderDate?: string;
  reason?: string;
  actualDeliveredQty?: number | string;
  deliveredDate?: string;
  [key: string]: unknown;
}

export interface ShopOrderReplenishmentReportResponse {
  rows: ShopOrderReplenishmentReportRow[];
}

const SHEET_NAME = "店鋪訂單補貨記錄";

const NO_DATA_NOTE =
  "（篩選範圍內無資料 / No records in the selected range）";

function emptySheetRow(note: string = NO_DATA_NOTE): Record<string, unknown> {
  return {
    "Shop No. / 店鋪編號": note,
    "Shop Name / 店鋪名稱": "",
    "Shop Order Date / 店鋪訂單日期": "",
    "Shop Order No. / 店鋪訂單編號": "",
    "Item No. / 貨品編號": "",
    "Item Name / 貨品名稱": "",
    "First Order Qty / 原訂單數量": "",
    "First Order Actual Pick Qty / 原單實際提料數量": "",
    "Reorder Qty / 補貨數量": "",
    "Reorder Date / 補貨日期": "",
    "Reason / 補貨原因": "",
    "Actual Delivered Qty / 實際補貨數量": "",
    "Delivered Date / 送貨日期": "",
  };
}

function formatReason(reason: string | undefined): string {
  switch ((reason ?? "").trim()) {
    case "quality_issue":
      return "質素問題";
    case "out_of_stock":
      return "缺貨";
    case "other":
      return "其他";
    default:
      return reason ?? "";
  }
}

function formatDateCell(value: unknown): string {
  if (value == null || value === "") return "";
  if (typeof value === "number" && Number.isFinite(value)) {
    // Jackson may serialize java.sql.Date as epoch millis or seconds
    const ms = value > 1e12 ? value : value * 1000;
    const d = new Date(ms);
    if (Number.isNaN(d.getTime())) return String(value);
    return d.toISOString().slice(0, 10);
  }
  const s = String(value).trim();
  if (/^\d{10,13}$/.test(s)) {
    const n = Number(s);
    const ms = s.length >= 13 ? n : n * 1000;
    const d = new Date(ms);
    if (!Number.isNaN(d.getTime())) return d.toISOString().slice(0, 10);
  }
  // JDBC / string date: "2026-08-01" or "2026-08-01 00:00:00.0"
  return s.length >= 10 ? s.slice(0, 10) : s;
}

function formatQty(value: unknown): string | number {
  if (value === null || value === undefined || value === "") return "";
  const n = typeof value === "number" ? value : Number(value);
  if (!Number.isFinite(n)) return String(value);
  return n;
}

function toExcelRow(r: ShopOrderReplenishmentReportRow): Record<string, unknown> {
  const base = emptySheetRow("");
  return {
    ...base,
    "Shop No. / 店鋪編號": r.shopNo ?? "",
    "Shop Name / 店鋪名稱": r.shopName ?? "",
    "Shop Order Date / 店鋪訂單日期": formatDateCell(r.shopOrderDate),
    "Shop Order No. / 店鋪訂單編號": r.shopOrderNo ?? "",
    "Item No. / 貨品編號": r.itemNo ?? "",
    "Item Name / 貨品名稱": r.itemName ?? "",
    "First Order Qty / 原訂單數量": formatQty(r.firstOrderQty),
    "First Order Actual Pick Qty / 原單實際提料數量": formatQty(r.firstOrderActualPickQty),
    "Reorder Qty / 補貨數量": formatQty(r.reorderQty),
    "Reorder Date / 補貨日期": formatDateCell(r.reorderDate),
    "Reason / 補貨原因": formatReason(r.reason),
    "Actual Delivered Qty / 實際補貨數量": formatQty(r.actualDeliveredQty),
    "Delivered Date / 送貨日期": formatDateCell(r.deliveredDate),
  };
}

export async function fetchShopOrderReplenishmentReportData(
  criteria: Record<string, string>,
): Promise<ShopOrderReplenishmentReportRow[]> {
  const queryParams = new URLSearchParams(criteria).toString();
  const url = `${NEXT_PUBLIC_API_URL}/report/shop-order-replenishment?${queryParams}`;

  const response = await clientAuthFetch(url, {
    method: "GET",
    headers: { Accept: "application/json" },
  });

  if (response.status === 401 || response.status === 403)
    throw new Error("Unauthorized");
  if (!response.ok)
    throw new Error(`HTTP error! status: ${response.status}`);

  const data = (await response.json()) as
    | ShopOrderReplenishmentReportResponse
    | ShopOrderReplenishmentReportRow[];
  if (Array.isArray(data)) return data;
  return data.rows ?? [];
}

/**
 * Generate and download Shop Orders Replenishment Records as Excel.
 */
export async function generateShopOrderReplenishmentReportExcel(
  criteria: Record<string, string>,
  reportTitle: string = "店鋪訂單補貨記錄",
): Promise<void> {
  const rows = await fetchShopOrderReplenishmentReportData(criteria);
  const excelRows =
    rows.length > 0 ? rows.map(toExcelRow) : [emptySheetRow()];

  const dateCandidates = [
    criteria.reorderDateStart,
    criteria.reorderDateEnd,
    criteria.shopOrderDateStart,
    criteria.shopOrderDateEnd,
    criteria.deliveredDateStart,
    criteria.deliveredDateEnd,
  ].filter((v) => (v ?? "").trim().length > 0);
  const datePart =
    dateCandidates.length > 0
      ? dateCandidates.join("_")
      : new Date().toISOString().slice(0, 10);
  const safeDatePart = datePart.replace(/[^\d\-_/]/g, "");
  const filename = `${reportTitle}_${safeDatePart}`;

  exportChartToXlsx(excelRows, filename, SHEET_NAME);
}
