export default function useCleaningSchedules() {
  const _cleanerChecklists = ref({
    _id: "",
    date: "",
    status: [],
    createdAt: "",
    updatedAt: "",
    attachments: [],
  });

  async function getCleaningSchedules({
    site = "",
    search = "",
    page = 1,
    limit = 10,
    startDate = "",
    endDate = "",
    status = "",
    serviceType = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-parent-checklist/site/${site}`,
      {
        method: "GET",
        query: {
          search,
          page,
          limit,
          startDate,
          endDate,
          status,
          serviceType,
        },
      },
    );
  }

  async function getScheduleAreas({
    scheduleAreaId = "",
    page = 1,
    limit = 10,
    search = "",
    status = "",
    type = "",
    serviceType = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/schedule/${scheduleAreaId}`,
      {
        method: "GET",
        query: {
          search,
          page,
          limit,
          status,
          type,
          serviceType,
        },
      },
    );
  }

  function acceptAreaChecklist(id: string) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${id}/accept`,
      {
        method: "PATCH",
      },
    );
  }

  async function getUnitCleanerChecklist({
    scheduleAreaId = "",
    page = 1,
    limit = 10,
    search = "",
    serviceType = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${scheduleAreaId}/units`,
      {
        method: "GET",
        query: {
          search,
          page,
          limit,
          serviceType,
        },
      },
    );
  }

  function updateUnitChecklist(
    checklistId: string,
    unitId: string,
    set: number,
    decision: "approve" | "reject",
    remarks?: string,
    attachment?: string[],
  ) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${checklistId}/set/${set}/units/${unitId}/${decision}`,
      {
        method: "PATCH",
        body: { remarks, attachment },
      },
    );
  }

  function updateAreaChecklistStatus(
    id: string,
    status: "complete" | "submit",
    signature: string,
  ) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${id}/${status}`,
      {
        method: "PATCH",
        body: { signature },
      },
    );
  }

  function uploadAreaChecklistAttachment(id: string, attachments: string[]) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${id}/upload`,
      {
        method: "PATCH",
        body: { attachments },
      },
    );
  }

  function generateChecklist(site: string, parentChecklistId: string) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/site/${site}/schedule/${parentChecklistId}`,
      {
        method: "POST",
      },
    );
  }

  async function getAreaChecklistHistory({
    parentChecklistId = "",
    page = 1,
    limit = 10,
    search = "",
    status = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/schedule/${parentChecklistId}/history`,
      {
        method: "GET",
        query: { page, limit, search, status },
      },
    );
  }

  async function getAreaChecklistHistoryById(id: string) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/hygiene-area-checklist/id/${id}/history`,
      {
        method: "GET",
      },
    );
  }

  async function exportAreas(site: string) {
    const res = await useNuxtApp().$api<Blob | MediaSource>(
      `/api/hygiene-area/site/${site}/download`,
      {
        method: "GET",
      },
    );

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

    const date = new Date();
    const formattedDate = `${String(date.getMonth() + 1).padStart(
      2,
      "0",
    )}-${String(date.getDate()).padStart(2, "0")}-${date.getFullYear()}`;

    const downloadUrl = window.URL.createObjectURL(res);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = `areas-${formattedDate}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(downloadUrl);
  }

  async function downloadChecklistPdf(scheduleId: string) {
    const res = await useNuxtApp().$api<Blob | MediaSource>(
      `/api/hygiene-area-checklist/schedule/${scheduleId}/pdf`,
      {
        method: "GET",
        responseType: "blob",
      },
    );

    if (!res) throw new Error("Error downloading checklist PDF");

    const date = new Date();
    const formattedDate = `${String(date.getDate()).padStart(2, "0")}_${String(
      date.getMonth() + 1,
    ).padStart(2, "0")}_${date.getFullYear()} ${String(
      date.getHours(),
    ).padStart(2, "0")}_${String(date.getMinutes()).padStart(2, "0")}`;

    const downloadUrl = window.URL.createObjectURL(res);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = `CHECKLIST_DOWNLOADED_${formattedDate}.pdf`;
    a.target = "_blank";
    a.rel = "noopener noreferrer";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(() => window.URL.revokeObjectURL(downloadUrl), 1000);
  }

  return {
    _cleanerChecklists,
    getCleaningSchedules,
    getScheduleAreas,
    acceptAreaChecklist,
    updateUnitChecklist,
    getUnitCleanerChecklist,
    updateAreaChecklistStatus,
    uploadAreaChecklistAttachment,
    generateChecklist,
    getAreaChecklistHistory,
    getAreaChecklistHistoryById,
    exportAreas,
    downloadChecklistPdf,
  };
}
