export default function useCustomer() {
  const customers = ref<Array<TCustomer>>([]);
  const page = ref(1);
  const pages = ref(0);
  const pageRange = ref("-- - -- of --");
  const search = ref("");

  const customer = useState(
    "customer",
    (): TCustomer => ({
      _id: "",
      name: "",
      orgId: "",
      customerOrgId: "",
      createdAt: "",
      updatedAt: "",
    })
  );

  async function getCustomers({
    page = 1,
    search = "",
    limit = 10,
    organization,
    status = "active",
    sort = "",
    order = "asc",
  }: {
    page?: number;
    search?: string;
    limit?: number;
    organization?: string;
    status?: string;
    sort?: string;
    order?: string;
  } = {}) {
    const { currentUser } = useLocalAuth();

    const orgId = organization || currentUser.value?.defaultOrg;

    try {
      const response = await useNuxtApp().$api<TCustomerPaginatedResponse>(
        `/api/customers/organization/${orgId}/status/${status}`,
        {
          method: "GET",
          query: { page, search, limit, sort, order },
        }
      );

      customers.value = response.items;
      pages.value = response.pages;
      pageRange.value = response.pageRange;
    } catch (err) {
      console.error("Error fetching customers:", err);
    }
  }

  function createCustomer(payload: TCustomerCreate) {
    return useNuxtApp().$api<Record<string, any>>(`/api/customers`, {
      method: "POST",
      body: payload,
    });
  }

  function deleteCustomer(id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/customers/${id}`, {
      method: "DELETE",
    });
  }

  function getCustomerById(id: string) {
    return useNuxtApp().$api<TCustomer>(`/api/customers/${id}`, {
      method: "GET",
    });
  }

  async function getAll({
    page = 1,
    search = "",
    limit = 10,
    org = "",
    status = "active",
    sort = "",
    order = "asc",
  }: {
    page?: number;
    search?: string;
    limit?: number;
    org?: string;
    status?: string;
    sort?: string;
    order?: string;
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/customers", {
      method: "GET",
      query: { page, search, limit, sort, order, status, org },
    });
  }

  return {
    customers,
    customer,
    page,
    pages,
    pageRange,
    search,
    getCustomers,
    deleteCustomer,
    createCustomer,
    getCustomerById,
    getAll,
  };
}
