'use client'

import { useQueryClient } from '@tanstack/react-query'

import type { IBaseResponse } from '@/@core/types/api'
import type { IOrder, IOrderCustomerAddress, IOrderItemInput, ORDER_STATUS, PAYMENT_STATUS } from '@/types/data'
import { request } from '@/utils'
import { ORDERS_LIST_QUERY_KEY } from './useGetOrders'
import { ORDER_DETAILS_QUERY_KEY } from './useGetOrderDetails'
import { useMemo } from 'react'
import { SecondaryAction } from '@/views/orders/order/orderConstants'
import { useCustomMutation } from '@/hooks/api'

const invalidateOrderQueries = async (queryClient: ReturnType<typeof useQueryClient>, orderId?: string) => {
  const tasks = [queryClient.invalidateQueries({ queryKey: [ORDERS_LIST_QUERY_KEY] })]

  if (orderId) {
    tasks.push(queryClient.invalidateQueries({ queryKey: [ORDER_DETAILS_QUERY_KEY, orderId] }))
  }

  await Promise.all(tasks)
}

type UpdateOrderStatusPayload = {
  orderId: string
  status: ORDER_STATUS
  cancellation_reason?: string
}

type UpdateOrderPaymentPayload = {
  orderId: string
  payment_status: PAYMENT_STATUS
  payment_method?: string
}

type UpdateOrderItemsPayload = {
  orderId: string
  items: IOrderItemInput[]
}

type CancelOrderPayload = {
  orderId: string
  cancellation_reason: string
}

type UpdateFeePayload = {
  orderId: string
  value: number
}

type UpdateTaxPayload = {
  orderId: string
  tax_rate?: number
  tax_amount?: number
}

type UpdateNotesPayload = {
  orderId: string
  notes: string
}

type UpdateAddressPayload = {
  orderId: string
  address: IOrderCustomerAddress
}

type UpdateTablePayload = {
  orderId: string
  table_id: string
}

type UpdateEstimatePayload = {
  orderId: string
  estimated_delivery_time?: string
  pickup_time?: string
}

type UpdateOrderPayload = {
  orderId: string
  data: Record<string, any>
}

export const useUpdateOrderStatus = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateOrderStatusPayload, IBaseResponse<IOrder>>(
    ['orders-update-status'],
    ({ orderId, ...payload }) =>
      request({
        url: `/orders/${orderId}/status`,
        method: 'PATCH',
        data: payload
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderPayment = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateOrderPaymentPayload, IBaseResponse<IOrder>>(
    ['orders-update-payment'],
    ({ orderId, ...payload }) =>
      request({
        url: `/orders/${orderId}/payment`,
        method: 'PATCH',
        data: payload
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderItems = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateOrderItemsPayload, IBaseResponse<IOrder>>(
    ['orders-update-items'],
    ({ orderId, items }) =>
      request({
        url: `/orders/${orderId}/items`,
        method: 'PATCH',
        data: { items }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useCancelOrder = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<CancelOrderPayload, IBaseResponse<IOrder>>(
    ['orders-cancel'],
    ({ orderId, cancellation_reason }) =>
      request({
        url: `/orders/${orderId}/cancel`,
        method: 'PATCH',
        data: { cancellation_reason }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateDeliveryFee = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateFeePayload, IBaseResponse<IOrder>>(
    ['orders-update-delivery-fee'],
    ({ orderId, value }) =>
      request({
        url: `/orders/${orderId}/delivery-fee`,
        method: 'PATCH',
        data: { delivery_fee: value }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateServiceFee = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateFeePayload, IBaseResponse<IOrder>>(
    ['orders-update-service-fee'],
    ({ orderId, value }) =>
      request({
        url: `/orders/${orderId}/service-fee`,
        method: 'PATCH',
        data: { service_fee: value }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderTax = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateTaxPayload, IBaseResponse<IOrder>>(
    ['orders-update-tax'],
    ({ orderId, ...payload }) =>
      request({
        url: `/orders/${orderId}/tax`,
        method: 'PATCH',
        data: payload
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderDiscount = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateFeePayload, IBaseResponse<IOrder>>(
    ['orders-update-discount'],
    ({ orderId, value }) =>
      request({
        url: `/orders/${orderId}/discount`,
        method: 'PATCH',
        data: { discount_amount: value }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderNotes = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateNotesPayload, IBaseResponse<IOrder>>(
    ['orders-update-notes'],
    ({ orderId, notes }) =>
      request({
        url: `/orders/${orderId}/notes`,
        method: 'PATCH',
        data: { notes }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderDeliveryAddress = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateAddressPayload, IBaseResponse<IOrder>>(
    ['orders-update-address'],
    ({ orderId, address }) =>
      request({
        url: `/orders/${orderId}/delivery-address`,
        method: 'PATCH',
        data: address
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderTable = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateTablePayload, IBaseResponse<IOrder>>(
    ['orders-update-table'],
    ({ orderId, table_id }) =>
      request({
        url: `/orders/${orderId}/table`,
        method: 'PATCH',
        data: { table_id }
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrderEstimate = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateEstimatePayload, IBaseResponse<IOrder>>(
    ['orders-update-estimate'],
    ({ orderId, ...payload }) =>
      request({
        url: `/orders/${orderId}/estimated-time`,
        method: 'PATCH',
        data: payload
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useUpdateOrder = () => {
  const queryClient = useQueryClient()

  return useCustomMutation<UpdateOrderPayload, IBaseResponse<IOrder>>(
    ['orders-update'],
    ({ orderId, data }) =>
      request({
        url: `/orders/${orderId}`,
        method: 'PUT',
        data
      }),
    {
      onSuccess: async (_, variables) => {
        await invalidateOrderQueries(queryClient, variables.orderId)
      }
    }
  )
}

export const useOrderActions = (t: (key: string) => string) => {
  return useMemo(
    () => [
      {
        key: 'delivery_fee' as SecondaryAction,
        label: t('actions.deliveryFee'),
        icon: 'tabler-scooter',
        color: 'info'
      },
      {
        key: 'service_fee' as SecondaryAction,
        label: t('actions.serviceFee'),
        icon: 'tabler-receipt-2',
        color: 'success'
      },
      { key: 'tax' as SecondaryAction, label: t('actions.tax'), icon: 'tabler-percentage', color: 'warning' },
      { key: 'discount' as SecondaryAction, label: t('actions.discount'), icon: 'tabler-ticket', color: 'secondary' },
      { key: 'notes' as SecondaryAction, label: t('actions.notes'), icon: 'tabler-notebook', color: 'primary' },
      {
        key: 'table' as SecondaryAction,
        label: t('actions.table'),
        icon: 'tabler-square-rounded-number-1',
        color: 'primary'
      },
      {
        key: 'estimate' as SecondaryAction,
        label: t('actions.estimate'),
        icon: 'tabler-calendar-time',
        color: 'warning'
      },
      { key: 'cancel' as SecondaryAction, label: t('actions.cancel'), icon: 'tabler-circle-x', color: 'error' }
    ],
    [t]
  )
}
