'use client'

import { IBaseResponse, IPaginatedData, CustomUseQueryOptions, TPaginationModel } from '@/@core/types/api'
import { useCustomQuery } from '@/hooks/api'
import type { ORDER_STATUS, ORDER_TYPE, PAYMENT_STATUS, IOrder } from '@/types/data'
import { request } from '@/utils'

export const ORDERS_LIST_QUERY_KEY = 'orders-list'

export type OrdersSortField = 'created_at' | 'total_amount' | 'order_number'

type OrdersListFilters = {
  status?: ORDER_STATUS
  payment_status?: PAYMENT_STATUS
  order_type?: ORDER_TYPE
  date_from?: string
  date_to?: string
  search?: string
  sort_by?: OrdersSortField
  sort_as?: 'asc' | 'desc'
  with_relations?: 1
  with_relations_count?: 1
}

type OrdersListQueryBase = TPaginationModel & OrdersListFilters

export type OrdersListNoPaginateQuery = OrdersListFilters & {
  with_paginate: 'no'
}

export const useGetOrdersList: {
  (
    query: OrdersListNoPaginateQuery,
    options?: CustomUseQueryOptions<IBaseResponse<IOrder[]>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<IOrder[]>>>

  (
    query?: OrdersListQueryBase,
    options?: CustomUseQueryOptions<IBaseResponse<IPaginatedData<IOrder[]>>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<IPaginatedData<IOrder[]>>>>
} = (query?: OrdersListQueryBase | OrdersListNoPaginateQuery, options?: CustomUseQueryOptions<IBaseResponse<any>>) => {
  const queryKey = [ORDERS_LIST_QUERY_KEY, query]

  const ordersList = useCustomQuery<IBaseResponse<any>>(
    queryKey,
    () => {
      const params: Record<string, string> = {}

      if (!query || query.with_paginate !== 'no') {
        params.page = String(query?.page ?? 1)
        params.per_page = String(query?.per_page ?? 10)
      }

      if (query) {
        Object.entries(query).forEach(([key, value]) => {
          if (
            value !== undefined &&
            value !== null &&
            value !== '' &&
            key !== 'page' &&
            key !== 'per_page' &&
            key !== 'with_paginate'
          ) {
            params[key] = String(value)
          }
        })

        if (query.with_paginate === 'no') {
          params.with_paginate = 'no'
        }
      }

      return request({ url: '/orders', params })
    },
    options
  )

  return ordersList
}
