export default function useBillingUnits() {
  class MBillingUnits implements TBillingUnits {
    _id?: string; // Used for Reference only temporary
    billId?: string;
    unitId?: string;
    unit?: string; // Block / Level / Unit
    unitOwner?: string;
    email?: string; // Prompt user of their invoice via email
    contactNumber?: string;
    category?: string;
    dueDate?: string | Date; // Due date of this unit bill
    startDate?: string | Date; // Start date of billing period
    preDueDateAlert?: string; // Date when the bill was sent (ex. 5 days before the dueDate)
    startPaymentDate?: string | Date; // Days set before the dueDate (preDueDateAlert - dueDate)
    referenceNumber?: string; // ex. INV-IDNo.-Date-0001
    paymentStatus?: string;
    amountPaid?: string | number; // Paid for amount
    balance?: string | number; // If paymentStatus is partial, then there is always a balance
    billStatus?: string; // Active or Inactive
    paidBy?: string; // Management or resident
    datePaid?: string | Date;
    transaction_id?: string; // this is coming from RDP transaction
    billDetails: TBillDetails;
    constructor(data: Partial<TBillingUnits> = {}) {
      this._id = data._id || "";
      this.billId = data.billId || "";
      this.unitId = data.unitId || "";
      this.unit = data.unit || "";
      this.unitOwner = data.unitOwner || "";
      this.email = data.email || "";
      this.contactNumber = data.contactNumber || "";
      this.category = data.category || "";
      this.dueDate = data.dueDate || new Date();
      this.startDate = data.startDate || new Date();
      this.preDueDateAlert = data.preDueDateAlert || "";
      this.startPaymentDate = data.startPaymentDate || new Date();
      this.referenceNumber = data.referenceNumber || "";
      this.paymentStatus = data.paymentStatus || "";
      this.amountPaid = data.amountPaid || 0;
      this.balance = data.balance || 0;
      this.billStatus = data.billStatus || "";
      this.paidBy = data.paidBy || "";
      this.datePaid = data.datePaid || "";
      this.billDetails = data.billDetails || ({} as TBillDetails);
    }
  }

  const apiEndPoint = "api/unit-bill/v1";
  const item = useState("unit-bill", () => new MBillingUnits());
  const items = useState("unit-bills", (): TBillingUnits[] => []);
  const page = useState("unit-billPage", () => 1);
  const pages = useState("unit-billPages", () => 1);
  const itemsPerPage = useState("unit-billItemsPerPage", () => 10);
  const pageRange = useState("unit-billPageRange", () => "-- - -- of --");
  const search = useState("unit-billSearch", () => "");
  const filter = useState("billing-ticketSearch", () => "");
  const filterOptions = useState("unit-billFilterOptions", () => []);
  const isLoading = useState("unit-billIsLoading", () => false);
  const isAdding = useState("unit-billIsAdding", () => false);
  const isUpdating = useState("unit-billIsUpdating", () => false);
  const isDeleting = useState("unit-billIsDeleting", () => false);
  const isValid = useState("unit-billIsValid", () => false);

  // DOWNLOAD SCREENSHOT
  function downloadInvoice(url: string, title?: string) {
    const params = new URLSearchParams();

    if (url) params.set("url", String(url));
    params.set("title", String(title || "Unknown Title"));
    params.set("orientation", String("P"));
    // Make the request to the updated backend API endpoint that returns an image (PNG)
    const res = useNuxtApp().$api(
      `/${apiEndPoint}/image?${params.toString()}` // Updated API endpoint that handles the image (instead of /pdf)
    );

    if (!res) throw new Error("Error downloading image");

    const downloadUrl = window.URL.createObjectURL(res); // Create an object URL for the Blob
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = `${title || "DOCUMENT"}_DOWNLOADED_${formatDateString(
      new Date(),
      "mm-dd-yyyy"
    )}.png`; // Set filename for download
    document.body.appendChild(a);
    a.click(); // Trigger the download
    window.URL.revokeObjectURL(downloadUrl); // Clean up the object URL
  }

  // GET UNIT BILL BY REFERENCE NUMBER
  function getUnitBillByRef(id: string) {
    const params = new URLSearchParams();
    if (id) params.set("refId", String(id));
    isLoading.value = true;
    const response = useNuxtApp().$api(
      `/${apiEndPoint}/unit-bill/ref-id?${params.toString()}`
    );
    isLoading.value = false;
    return response;
  }

  // GET UNIT CART BY REFERENCE NUMBER
  function getUnitCartByRef(id: string) {
    const params = new URLSearchParams();
    if (id) params.set("refId", String(id));
    isLoading.value = true;
    const response = useNuxtApp().$api(
      `/${apiEndPoint}/unit-cart/ref-id?${params.toString()}`
    );
    isLoading.value = false;
    return response;
  }

  return {
    item,
    items,
    page,
    pages,
    itemsPerPage,
    pageRange,
    isValid,
    isLoading,
    isAdding,
    isUpdating,
    isDeleting,
    filter,
    filterOptions,
    search,
    downloadInvoice,
    getUnitBillByRef,
    getUnitCartByRef,
  };
}
