'use client'

import { useMemo } from 'react'

import { IBaseResponse, CustomUseQueryOptions } from '@/@core/types/api'
import { useCustomQuery } from '@/hooks/api'
import { IPaymentLink } from '@/types'
import { request } from '@/utils'

export const PAYMENT_LINKS_QUERY_KEY = 'payment-links-list'

export type PaymentLinkStatus = 'pending' | 'paid' | 'failed' | 'cancelled'

export type PaymentLinksFilters = {
  search?: string
  status?: PaymentLinkStatus[]
  amount_min?: number
  amount_max?: number
  created_from?: string
  created_to?: string
  expires_from?: string
  expires_to?: string
  paid_from?: string
  paid_to?: string
  sort_by?: 'created_at' | 'updated_at' | 'expires_at' | 'paid_at' | 'amount'
  sort_as?: 'asc' | 'desc'
  per_page?: number
  page?: number
}

const buildParams = (filters?: PaymentLinksFilters) => {
  if (!filters) return undefined

  const params: Record<string, string | number> = {}

  if (filters.search) params.search = filters.search
  if (filters.status && filters.status.length) params.status = filters.status.join(',')
  if (typeof filters.amount_min === 'number') params.amount_min = filters.amount_min
  if (typeof filters.amount_max === 'number') params.amount_max = filters.amount_max
  if (filters.created_from) params.created_from = filters.created_from
  if (filters.created_to) params.created_to = filters.created_to
  if (filters.expires_from) params.expires_from = filters.expires_from
  if (filters.expires_to) params.expires_to = filters.expires_to
  if (filters.paid_from) params.paid_from = filters.paid_from
  if (filters.paid_to) params.paid_to = filters.paid_to
  if (filters.sort_by) params.sort_by = filters.sort_by
  if (filters.sort_as) params.sort_as = filters.sort_as
  if (typeof filters.per_page === 'number') params.per_page = filters.per_page
  if (typeof filters.page === 'number') params.page = filters.page

  return params
}

export const useGetPaymentLinks = (
  filters?: PaymentLinksFilters,
  options?: CustomUseQueryOptions<IBaseResponse<{ payment_links: IPaymentLink[] }>>
) => {
  const params = useMemo(() => buildParams(filters), [filters])

  return useCustomQuery<IBaseResponse<{ payment_links: IPaymentLink[] }>>(
    [PAYMENT_LINKS_QUERY_KEY, params],
    () =>
      request({
        url: 'admin/payment/links',
        params
      }),
    {
      ...options
    }
  )
}
