export default function usePassKey() {
  class MPassKey implements TPassKey {
    _id?: string;
    passId?: string;
    templateId?: string;
    templateName?: string;
    prefixAndName?: string;
    roomName?: string;
    createdAt?: Date;
    site: string;
    status?: string;

    constructor(
      {
        _id = "",
        passId = "",
        templateId = "",
        templateName = "",
        prefixAndName = "",
        roomName = "",
        createdAt,
        site = "",
        status = "",
      } = {} as TPassKey
    ) {
      this._id = _id;
      this.passId = passId;
      this.templateId = templateId;
      this.templateName = templateName;
      this.prefixAndName = prefixAndName;
      this.roomName = roomName;
      this.createdAt = createdAt;
      this.site = site;
      this.status = status;
    }
  }
  const tab = useState("passKeyTab", () => "pass");
  const passKey = useState("passKey", () => new MPassKey());
  const passKeys = useState("passKeys", (): TPassKey[] => []);
  const page = useState("passKeyPage", () => 1);
  const pages = useState("passKeyPages", () => 0);
  const itemsPerPage = useState("itemsPerPage", () => 10);
  const search = useState("passKeySearch", () => "");
  const filterByTemplateName = useState("filterByTemplateName", () => "All");
  const pageRange = useState("passKeyPageRange", () => "-- - -- of --");
  const isPassKeysLoading = useState("isPassKeysLoading", () => false);

  const isPassListLoading = useState("isPassListLoading", () => false);
  const isKeyListLoading = useState("isKeyListLoading", () => false);

  const canNextPage = computed(() => pages.value > page.value);
  const canPrevPage = computed(() => page.value <= 1);

  const dialog = useState("passKeysDialog", () => false);
  const dialogType = useState("passKeysDialogType", () => "");
  const generatePass = useState("passKeysGeneratePass", () => false);

  const selectedTemplate = useState("passKeySelectedTemplate", (): any => null);

  const selectedKeysToPrint = useState("passKeysSelectedToPrint", () => []);

  function getNextNumber(
    { template = "", passType = "", site = "" } = {} as {
      template?: any | null;
      passType?: any | null;
      site?: string;
    }
  ) {
    return useNuxtApp().$api("/api/keys/generate/v1", {
      method: "PATCH",
      body: {
        template,
        passType,
        site,
      },
    });
  }

  function setPassKey(data?: TPassKey) {
    passKey.value = data || new MPassKey();
  }

  function setPassKeys(
    { search, passTypes, template, sites, statuses } = {} as {
      search?: string;
      passTypes?: string[] | null;
      template?: any | null;
      sites?: string[];
      statuses?: string[] | null;
    }
  ) {
    try {
      isPassKeysLoading.value = true;
      const _passKeys = getPassKeysByPageSearch({
        page: page.value,
        search,
        passTypes,
        template,
        sites,
        statuses,
      }) as any;

      console.log("_passKeys.items", _passKeys.items);

      passKeys.value = _passKeys.items as TPassKey[];
      pageRange.value = _passKeys.pageRange;
      pages.value = _passKeys.pages;
      isPassKeysLoading.value = false;
    } catch (error) {
      passKeys.value = [];
      pageRange.value = "-- - -- of --";
      pages.value = 0;
      isPassKeysLoading.value = false;
    }
  }

  function getPassKeysByPageSearch({
    _ids = [],
    page = 1,
    limit = 10,
    search = "",
    passTypes = [],
    template = "",
    sites = [],
    passOrKey = "",
    statuses = [],
    sortBy,
    prefixAndName,
  }: {
    _ids?: any;
    page?: number;
    limit?: number;
    search?: string;
    passTypes?: string[] | null;
    template?: any | null;
    sites?: string[];
    passOrKey?: string;
    statuses?: string[] | null;
    sortBy?: object;
    prefixAndName?: string;
  }) {
    return useNuxtApp().$api("/api/keys/search/v1", {
      method: "POST",
      body: {
        _ids,
        page,
        limit,
        search,
        passTypes,
        template,
        sites,
        passOrKey,
        statuses,
        sortBy,
        prefixAndName,
      },
    });
  }

  function deleteHidCard({
    site = "",
    cardNo = "",
  }: {
    site?: string;
    cardNo?: string;
  }) {
    isPassKeysLoading.value = true;
    const params = new URLSearchParams();
    if (cardNo) params.append("cardId", cardNo);

    try {
      return useNuxtApp().$api(
        `/api/visitors/nfc/${site}?${params.toString()}`,
        {
          method: "PATCH",
        }
      );
    } catch (error: any) {
      return Promise.reject(error.value.data.message);
    } finally {
      isPassKeysLoading.value = false;
    }
  }

  function fetchHidLogs({
    site = "",
    purpose = "vms",
    page = 1,
    search = "",
    status = [],
  }: {
    site?: string;
    purpose?: "vms";
    page?: number;
    search?: string;
    status?: string[];
  }) {
    isPassKeysLoading.value = true;
    const params = new URLSearchParams();
    if (site) params.append("site", site);
    if (purpose) params.append("purpose", purpose);
    params.append("page", page.toString());
    if (search) params.append("search", search);

    const body: any = {};
    if (status && status.length > 0) {
      body.status = status.map((item: any) => item.value);
    }

    const result: any = useNuxtApp().$api(
      `/api/visitors/nfc/${params.get("site")}?${params.toString()}`,
      {
        method: "POST",
        body: Object.keys(body).length > 0 ? body : undefined,
      }
    );

    passKeys.value = result.data.result.items;
    pageRange.value = result.data.result.pageRange;
    pages.value = result.data.result.pages;
    isPassKeysLoading.value = false;
  }

  function generatePassesKeys(
    {
      template = "",
      passType = "",
      site = "",
      quantity = 0,
      nextNumber = 0,
      userType,
      updatedBy,
    } = {} as {
      template?: any | null;
      passType?: any | null;
      site?: any;
      quantity?: number | null;
      nextNumber: number;
      userType?: string;
      updatedBy?: string;
    }
  ) {
    return useNuxtApp().$api("/api/keys/generate/v1", {
      method: "POST",
      body: {
        template,
        passType,
        site,
        quantity,
        nextNumber,
        userType,
        updatedBy,
      },
    });
  }

  function updatePassKeyStatus({
    _id,
    site,
    status,
  }: {
    _id?: string;
    site?: string;
    status?: string;
  }) {
    return useNuxtApp().$api("/api/qr-code-templates/v1", {
      method: "PUT",
      body: { _id, site, status },
    });
  }

  function getStatusHistories({
    _id,
    page = 1,
    limit = 10,
  }: {
    _id?: string;
    page?: number;
    limit?: number;
  }) {
    return useNuxtApp().$api("/api/keys/histories/v1", {
      method: "POST",
      body: { _id },
    });
  }

  function nextPage(
    { search, passTypes, template, sites, statuses } = {} as {
      search?: string;
      passTypes?: string[] | null;
      template?: any | null;
      sites?: string[];
      statuses?: string[] | null;
    }
  ) {
    page.value++;
    setPassKeys({
      search,
      passTypes,
      template,
      sites,
      statuses,
    });
  }

  function prevPage(
    { search, passTypes, template, sites, statuses } = {} as {
      search?: string;
      passTypes?: string[] | null;
      template?: any | null;
      sites?: string[];
      statuses?: string[] | null;
    }
  ) {
    page.value--;
    setPassKeys({
      search,
      passTypes,
      template,
      sites,
      statuses,
    });
  }

  return {
    tab,
    passKey,
    passKeys,
    search,
    filterByTemplateName,
    setPassKeys,
    setPassKey,
    getPassKeysByPageSearch,
    isPassKeysLoading,
    itemsPerPage,
    page,
    pages,
    pageRange,
    canNextPage,
    nextPage,
    prevPage,
    canPrevPage,
    getNextNumber,
    generatePassesKeys,
    updatePassKeyStatus,
    isPassListLoading,
    isKeyListLoading,
    dialog,
    dialogType,
    generatePass,
    selectedTemplate,
    selectedKeysToPrint,
    getStatusHistories,
    fetchHidLogs,
    deleteHidCard,
  };
}
