'use client'

import { useQuery } from '@tanstack/react-query'
import { request } from '@/utils'
import { IBaseResponse } from '@/@core/types/api'
import { ICategory } from '@/types/data/categories/category.interface'
import { IUpdateCategoryDto } from '@/types/data/categories/category-update.interface'
import { useCustomMutation } from '@/hooks/api'

export const CATEGORY_QUERY_KEY = 'category'
export const useGetCategory = (id: string) => {
  return useQuery<any>({
    queryKey: [CATEGORY_QUERY_KEY, id],
    queryFn: async () => {
      const res = await request({ url: `/categories/${id}`, method: 'GET' })
      return res.data
    },
    enabled: !!id
  })
}

export const useUpdateCategory = () => {
  return useCustomMutation<{ id: string; payload: IUpdateCategoryDto }, IBaseResponse<ICategory>>(
    ['categories-update'],
    async ({ id, payload }) => {
      let imageValue = payload.image ?? null
      if (typeof FileList !== 'undefined' && imageValue instanceof FileList) {
        imageValue = imageValue.item(0)
      }

      const basePayload = {
        name_ar: payload.name_ar,
        name_en: payload.name_en,
        description_ar: payload.description_ar ?? '',
        description_en: payload.description_en ?? '',
        sort_order: payload.sort_order,
        is_active: payload.is_active,
        parent_id: payload.parent_id
      }

      if (imageValue instanceof File) {
        const formData = new FormData()

        Object.entries(basePayload).forEach(([key, value]) => {
          if (value === undefined || value === null) return
          formData.append(key, String(value))
        })
        formData.append('image', imageValue)

        const res = await request<IBaseResponse<ICategory>>({
          url: `/categories/${id}`,
          method: 'PUT',
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        return res
      }

      const res = await request<IBaseResponse<ICategory>>({
        url: `/categories/${id}`,
        method: 'PUT',
        data: {
          ...basePayload,
          image: typeof imageValue === 'string' ? imageValue : null
        }
      })
      return res
    },
    {
      invalidateQueries: ['categories-list']
    }
  )
}

export const useDeleteCategory = () => {
  return useCustomMutation<string, IBaseResponse<void>>(['categories-delete'], async id => {
    const res = await request<IBaseResponse<void>>({
      url: `/categories/${id}`,
      method: 'DELETE'
    })
    return res
  })
}
