"use client";

import Swal from "sweetalert2";
import type { TFunction } from "i18next";
import { fetchPickRecordPlasticBoxCartonQty } from "@/app/api/jo/actions";

export type PickRecordFloor = "2F" | "3F" | "4F" | "ALL";

export interface AllFloorsPlasticBoxCartonQtyResult {
  qty2f: number;
  qty3f: number;
  qty4f: number;
  sum: number;
}

const inputStyle =
  "margin:0;flex:1;outline:none;box-shadow:none;border:1px solid #d9d9d9;";

/** Non-negative integers only; empty string allowed when allowEmpty. */
function parseWholeNumberQty(raw: string, allowEmpty: boolean): number | null {
  const trimmed = raw.trim();
  if (trimmed === "") {
    return allowEmpty ? 0 : null;
  }
  if (!/^\d+$/.test(trimmed)) {
    return null;
  }
  return parseInt(trimmed, 10);
}

function buildFloorQtyInputRow(
  inputId: string,
  label: string,
  placeholder: string,
  value: number | null | undefined,
): string {
  const valueAttr =
    value !== null && value !== undefined ? `value="${value}"` : "";
  return `
    <div style="display:flex;align-items:center;gap:12px;">
      <label for="${inputId}" style="min-width:140px;">${label}</label>
      <input id="${inputId}" class="swal2-input" type="number" min="0" step="1" inputmode="numeric" placeholder="${placeholder}" ${valueAttr} style="${inputStyle}" onfocus="this.style.outline='none';this.style.boxShadow='none';this.style.borderColor='#d9d9d9';" />
    </div>
  `;
}

function parseFloorQtyInput(inputId: string): number | null {
  const raw =
    (document.getElementById(inputId) as HTMLInputElement | null)?.value?.trim() ??
    "";
  return parseWholeNumberQty(raw, true);
}

export async function promptPlasticBoxCartonQty(
  t: TFunction,
): Promise<number | null> {
  const result = await Swal.fire({
    title: t("Enter plastic box carton qty"),
    icon: "info",
    input: "number",
    inputPlaceholder: t("Plastic box carton Qty"),
    inputAttributes: {
      min: "1",
      step: "1",
      inputmode: "numeric",
    },
    inputValidator: (value) => {
      if (!value) {
        return t("You need to enter a number");
      }
      const trimmed = String(value).trim();
      if (!/^\d+$/.test(trimmed)) {
        return t("Qty must be a whole number");
      }
      if (parseInt(trimmed, 10) < 1) {
        return t("Number must be at least 1");
      }
      return null;
    },
    showCancelButton: true,
    confirmButtonText: t("Confirm"),
    cancelButtonText: t("Cancel"),
    confirmButtonColor: "#8dba00",
    cancelButtonColor: "#F04438",
  });

  if (!result.isConfirmed) {
    return null;
  }

  const qty = parseWholeNumberQty(String(result.value ?? ""), false);
  if (qty === null || qty < 1) {
    return null;
  }
  return qty;
}

export async function promptAllFloorsPlasticBoxCartonQty(
  t: TFunction,
  pickOrderId: number,
): Promise<AllFloorsPlasticBoxCartonQtyResult | null> {
  let existing = {
    plasticBoxCartonQty2f: null as number | null,
    plasticBoxCartonQty3f: null as number | null,
    plasticBoxCartonQty4f: null as number | null,
  };
  try {
    existing = await fetchPickRecordPlasticBoxCartonQty(pickOrderId);
  } catch (e) {
    console.warn("Failed to load existing plastic box carton qty", e);
  }

  const placeholder = t("Plastic box carton Qty");
  const result = await Swal.fire({
    title: t("Enter all floors plastic box carton qty"),
    html: `
      <div style="display:flex;flex-direction:column;gap:10px;text-align:left;">
        ${buildFloorQtyInputRow("swal-qty-2f", t("2/F plastic box carton Qty"), placeholder, existing.plasticBoxCartonQty2f)}
        ${buildFloorQtyInputRow("swal-qty-3f", t("3/F plastic box carton Qty"), placeholder, existing.plasticBoxCartonQty3f)}
        ${buildFloorQtyInputRow("swal-qty-4f", t("4/F plastic box carton Qty"), placeholder, existing.plasticBoxCartonQty4f)}
      </div>
    `,
    showCancelButton: true,
    confirmButtonText: t("Confirm"),
    cancelButtonText: t("Cancel"),
    confirmButtonColor: "#8dba00",
    cancelButtonColor: "#F04438",
    focusConfirm: false,
    preConfirm: () => {
      const qty2f = parseFloorQtyInput("swal-qty-2f");
      const qty3f = parseFloorQtyInput("swal-qty-3f");
      const qty4f = parseFloorQtyInput("swal-qty-4f");

      if (qty2f === null || qty3f === null || qty4f === null) {
        Swal.showValidationMessage(t("Qty must be a whole number"));
        return null;
      }
      if (qty2f < 0 || qty3f < 0 || qty4f < 0) {
        Swal.showValidationMessage(t("Qty cannot be negative"));
        return null;
      }

      return {
        qty2f,
        qty3f,
        qty4f,
        sum: qty2f + qty3f + qty4f,
      } as AllFloorsPlasticBoxCartonQtyResult;
    },
  });

  if (!result.isConfirmed || !result.value) {
    return null;
  }
  return result.value as AllFloorsPlasticBoxCartonQtyResult;
}

export function buildPrintPickRecordRequest(params: {
  pickOrderId: number;
  printerId: number;
  printQty: number;
  floor: PickRecordFloor;
  plasticBoxCartonQty?: number;
  allFloorsQty?: AllFloorsPlasticBoxCartonQtyResult;
}) {
  if (params.floor === "ALL" && params.allFloorsQty) {
    return {
      pickOrderId: params.pickOrderId,
      printerId: params.printerId,
      printQty: params.printQty,
      floor: params.floor,
      plasticBoxCartonQty2f: params.allFloorsQty.qty2f,
      plasticBoxCartonQty3f: params.allFloorsQty.qty3f,
      plasticBoxCartonQty4f: params.allFloorsQty.qty4f,
    };
  }
  return {
    pickOrderId: params.pickOrderId,
    printerId: params.printerId,
    printQty: params.printQty,
    floor: params.floor,
    plasticBoxCartonQty: params.plasticBoxCartonQty!,
  };
}
