export interface ISearch {
  name?: string;
  passType: string;
}

export default function useKey() {
  class MKeyLog implements TKeyLog {
    _id?: string;
    name: string;
    codes?: string[];
    code?: string;
    site?: string;
    organization?: string;
    serviceProvider?: string;
    passType?: string; // Visitor Pass || Pass Key
    passId?: string;
    createdAt?: string;
    updatedAt?: string;
    location?: string;
    description?: string;
    qty?: number;
    nextNumber?: number;
    prefix?: string;
    keyNo?: number;
    userType?: string;
    updatedBy?: string;
    constructor(
      {
        _id = "",
        name = "",
        codes = [],
        code = "",
        site = "",
        organization = "",
        serviceProvider = "",
        passType = "",
        passId = "",
        createdAt,
        updatedAt,
        location = "",
        description = "",
        qty = 0,
        nextNumber = "",
        prefix = "",
        keyNo,
        userType,
        updatedBy,
      } = {} as TKeyLog
    ) {
      this._id = _id;
      this.name = name;
      this.codes = codes;
      this.passType = passType;
      this.passId = passId;
      this.codes = codes;
      this.codes = codes;
      this.site = site;
      this.organization = organization;
      this.serviceProvider = serviceProvider;
      this.createdAt = createdAt;
      this.updatedAt = updatedAt;
      this.location = location;
      this.description = description;
      this.qty = qty;
      this.nextNumber = Number(nextNumber);
      this.prefix = prefix;
      this.keyNo = keyNo;
      this.userType = userType;
      this.updatedBy = updatedBy;
    }
  }

  const keyLogApiUrl = "/api/keys/v1";
  const passApiUrl = "/api/keys/v1/pass";
  const keyApiUrl = "/api/keys/v1/keys";

  const keyLog = useState("keyLog", (): TKeyLog => new MKeyLog());
  const keyLogs = useState("keyLogs", (): TKeyLog[] => []);
  const page = useState("keyPage", () => 1);
  const pages = useState("keyPages", () => 1);
  const pageLimit = useState("keyLimit", () => 10);
  const pageRange = useState("keyPageRange", () => "-- - -- of --");
  const search = useState("keySearch", () => "");
  const isAdding = useState("isAdding", () => false);
  const isTableLoading = useState("isTableLoading", () => false);
  const isKeyLogValid = useState("isKeyLogValid", () => false);

  const passList = useState("passList", (): TKeyLog[] => []);
  const keyList = useState("keyList", (): TKeyLog[] => []);
  const passTypes = useState(
    "passTypes",
    () =>
      <any>[
        { title: "Visitor Pass", value: "visitor-pass" },
        { title: "Contractor Pass", value: "contractor-pass" },
        { title: "Agent Pass", value: "agent-pass" },
      ]
  );
  const passTypesStatus = useState("passTypesStatus", () => [
    { title: "Available", value: "Available" },
    { title: "In Use", value: "In Use" },
    { title: "Damaged", value: "Damaged" },
    { title: "Lost", value: "Lost" },
    { title: "Deleted", value: "Deleted" },
  ]);

  async function onSearchKey(term: string) {
    isTableLoading.value = true;
    const data = useNuxtApp().$api<string | undefined>(keyLogApiUrl, {
      method: "GET",
      query: {
        name: term,
      },
    });
    isTableLoading.value = false;
    return data;
  }

  function onFilterKeyByType(value: string) {
    isTableLoading.value = true;
    const data = useNuxtApp().$api<string | undefined>(keyLogApiUrl, {
      method: "GET",
      query: {
        passType: value,
      },
    });
    isTableLoading.value = false;
    return data;
  }

  function setKey(data?: TKeyLog) {
    console.log("data", data);
    keyLog.value = data || new MKeyLog();
  }

  function addKeyLog(_keyLog: TKeyLog) {
    isAdding.value = true;
    delete _keyLog._id;
    const data = useNuxtApp().$api<{
      message: string | undefined;
    }>(keyLogApiUrl, {
      method: "POST",
      body: JSON.stringify(_keyLog),
    });
    isAdding.value = false;
    return data.message;
  }

  function getKeyById(id: string) {
    const data = useNuxtApp().$api<TKeyLog | undefined>(
      `${keyLogApiUrl}/${id}`,
      {
        method: "GET",
      }
    );
    if (data && typeof data === "object") {
      setKey(data);
    }
    return data;
  }

  function updateKeyById(id: string, payload: TKeyLog) {
    payload.codes =
      payload.codes instanceof Array && payload.codes.length > 0
        ? payload.codes
        : [];
    const data = useNuxtApp().$api<{
      message: { acknowledged: boolean };
    }>(`${keyLogApiUrl}/${id}`, {
      method: "PUT",
      body: payload,
    });
    return data.message;
  }

  function deleteKeyById(id: string) {
    const data = useNuxtApp().$api<{ message: TKeyLog }>(
      `${keyLogApiUrl}/${id}`,
      {
        method: "DELETE",
        query: {
          _id: id,
        },
      }
    );
    return data;
  }

  function getKeysByKeyPageSearch({
    page = 1,
    search = "",
    limit = 10,
    site,
    serviceProvider,
    organization,
    startDateTime,
    endDateTime,
    statuses
  }: {
    page?: number;
    search?: string | ISearch;
    limit?: number;
    site?: string;
    serviceProvider?: string;
    organization?: string;
    startDateTime?: string;
    endDateTime?: string;
    statuses?: string[];
  } = {}) {
    /*
      search here should accept
      empty string or ISearch
    */
    return useNuxtApp().$api<TKeyLogResponse>(keyLogApiUrl, {
      method: "GET",
      query: {
        page,
        search,
        limit,
        site,
        serviceProvider,
        organization,
        startDateTime,
        endDateTime,
        statuses
      },
    });
  }

  function setKeyLogs(
    site?: string,
    serviceProvider?: string,
    organization?: string,
    startDate?: string,
    endDate?: string
  ) {
    try {
      isTableLoading.value = true;
      const _keyLogs = getKeysByKeyPageSearch({
        page: page.value,
        search: search.value,
        limit: pageLimit.value,
        site: site,
        serviceProvider: serviceProvider,
        organization: organization,
      });
      keyLogs.value = _keyLogs.items;
      pageRange.value = _keyLogs.pageRange;
      pages.value = _keyLogs.pages;
      isTableLoading.value = false;
    } catch (error) {
      keyLogs.value = [];
      pageRange.value = "-- - -- of --";
      isTableLoading.value = false;
    }
  }

  const canNextPage = computed(() => pages.value > page.value);
  function nextPage(
    { site, serviceProvider, startDate, endDate } = {} as {
      site?: string;
      serviceProvider?: string;
      startDate?: string;
      endDate?: string;
    }
  ) {
    page.value++;
    setKeyLogs(site, serviceProvider, undefined, startDate, endDate);
  }

  const canPrevPage = computed(() => page.value <= 1);
  function prevPage(
    { site, serviceProvider, startDate, endDate } = {} as {
      site?: string;
      serviceProvider?: string;
      startDate?: string;
      endDate?: string;
    }
  ) {
    page.value--;
    setKeyLogs(site, serviceProvider, undefined, startDate, endDate);
  }

  function getPassList(
    { site, serviceProvider, passType } = {} as {
      site?: string;
      serviceProvider?: string;
      passType?: string;
    }
  ) {
    const response = useNuxtApp().$api<TKeyLog[]>(passApiUrl, {
      method: "GET",
      query: {
        site,
        serviceProvider,
        passType,
      },
    });
    passList.value = response;
  }

  function getKeyList(
    { site, serviceProvider } = {} as {
      site?: string;
      serviceProvider?: string;
    }
  ) {
    const response = useNuxtApp().$api<TKeyLog[]>(keyApiUrl, {
      method: "GET",
      query: {
        site,
        serviceProvider,
      },
    });
    keyList.value = response;
  }

  function getCountTotalKeys(
    { site, userType } = {} as {
      site?: string;
      userType?: string;
    }
  ) {
    const response = useNuxtApp().$api<TKeyLog[]>(keyLogApiUrl, {
      method: "PATCH",
      body: {
        site,
        userType,
      },
    });
    keyList.value = response;
    console.log("keyList", keyList.value);
    return response;
  }

  async function getKeyWithSequence(
    { site, _id, userType, updatedBy } = {} as {
      site?: string;
      _id?: string;
      userType?: string;
      updatedBy?: string;
    }
  ) {
    const response = useNuxtApp().$api<TKeyLog[]>(keyLogApiUrl, {
      method: "PUT",
      body: {
        site,
        _id,
        userType,
        updatedBy,
      },
    });
    keyList.value = response;
    console.log("keyList", keyList.value);
    return response;
  }
  return {
    onSearchKey,
    onFilterKeyByType,
    deleteKeyById,
    updateKeyById,
    getKeyById,
    addKeyLog,
    setKeyLogs,
    setKey,
    nextPage,
    prevPage,
    page,
    pages,
    pageRange,
    pageLimit,
    canNextPage,
    canPrevPage,
    keyLogs,
    keyLog,
    isTableLoading,
    isAdding,
    isKeyLogValid,
    getPassList,
    getKeyList,
    passList,
    keyList,
    passTypes,
    passTypesStatus,
    getCountTotalKeys,
    getKeyWithSequence,
    getKeysByKeyPageSearch
  };
}
