import { useQuery } from '@tanstack/react-query'
import {
  CategoryReport,
  DashboardReport,
  InventoryReport,
  PaymentReport,
  ProductSalesReport,
  ProfitLossReport,
  SalesReport
} from '../../types/services/analytic'
import { api } from '../api'
import { formatDateDDMMYYYY } from '../../utils/transform'

interface AnalyticQueryParams {
  date_from?: string
  date_to?: string
}

export function useSalesAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<SalesReport>({
    queryKey: ['analytics-sales', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/sales?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useProductSalesAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<ProductSalesReport>({
    queryKey: ['analytics-products', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/products?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function usePaymentAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<PaymentReport>({
    queryKey: ['analytics-payment-methods', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/payment-methods?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useDashboardAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<DashboardReport>({
    queryKey: ['analytics-dashboard', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/dashboard?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useProfitLossAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<ProfitLossReport>({
    queryKey: ['analytics-profit-loss', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/profit-loss?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useCategoryAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  return useQuery<CategoryReport>({
    queryKey: ['analytics-categories', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/analytics/categories?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useInventoryAnalytics(params: AnalyticQueryParams = {}) {
  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const defaultDateTo = formatDateDDMMYYYY(today)
  const defaultDateFrom = formatDateDDMMYYYY(monthAgo)

  const { date_from = defaultDateFrom, date_to = defaultDateTo, ...filters } = params

  const user = (() => {
    try {
      return JSON.parse(localStorage.getItem('user') || '{}')
    } catch {
      return {}
    }
  })()

  const outletId = user?.outlet_id //

  return useQuery<InventoryReport>({
    queryKey: ['analytics-inventory', { date_from, date_to, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('date_from', date_from)
      queryParams.append('date_to', date_to)

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/inventory/report/details/${outletId}?${queryParams.toString()}`)
      return res.data.data
    }
  })
}
