import type { HomeDecor } from "./types"
import { apiClient } from "./client"
import type { PaginatedResponse, PaginationParams } from "./client"

function mapBackendHomeDecor(item: any): HomeDecor {
  const attrs = item.attributes || {}
  return {
    id: String(item.id),
    name: item.name,
    description: item.description || "",
    imageUrl: item.image_url || "",
    rarity: item.rarity_display || item.rarity || "",
    category: attrs.decoration_type || attrs.style || "",
    status: item.status_display || item.status || "",
    publishedAt: item.published_at || "",
    batchesCount: item.batches_count || 0,
    activeCardsCount: item.active_cards_count || 0,
    tags: attrs.placement ? [attrs.placement] : [],
    createdAt: item.created_at || "",
    updatedAt: item.updated_at || "",
  }
}

export const getHomeDecors = async (params?: PaginationParams): Promise<PaginatedResponse<HomeDecor>> => {
  const page = params?.page || 1
  const pageSize = params?.pageSize || 10
  const searchParam = params?.search ? `&search=${encodeURIComponent(params.search)}` : ""

  const response = await apiClient.get(
    `/card/category/decoration/?page=${page}&page_size=${pageSize}${searchParam}`
  )

  const data = response.data?.data || response.data
  const results: any[] = data.results || data
  const total = data.count || results.length

  return {
    items: results.map(mapBackendHomeDecor),
    total,
    page,
    pageSize,
    totalPages: Math.ceil(total / pageSize),
  }
}

export const getHomeDecor = async (id: string): Promise<HomeDecor> => {
  const response = await apiClient.get(`/card/templates/${id}/`)
  const data = response.data?.data || response.data
  return mapBackendHomeDecor(data)
}

export const createHomeDecor = async (decorData: Partial<HomeDecor> & { rarityValue?: string }): Promise<HomeDecor> => {
  const payload: any = {
    name: decorData.name,
    category: "decoration",
    description: decorData.description || "",
  }
  if (decorData.rarityValue) {
    payload.rarity = decorData.rarityValue
  }
  if (decorData.imageUrl) {
    payload.image_url = decorData.imageUrl
  }
  if (decorData.category) {
    payload.decoration_attributes = {
      decoration_type: decorData.category,
    }
  }

  const response = await apiClient.post(`/card/templates/`, payload)
  const data = response.data?.data || response.data
  return mapBackendHomeDecor(data)
}

export const updateHomeDecor = async (id: string, decorData: Partial<HomeDecor> & { rarityValue?: string }): Promise<HomeDecor> => {
  const payload: any = {}
  if (decorData.name !== undefined) payload.name = decorData.name
  if (decorData.description !== undefined) payload.description = decorData.description
  if (decorData.category !== undefined) payload.decoration_attributes = { decoration_type: decorData.category }
  if (decorData.rarityValue) payload.rarity = decorData.rarityValue
  if (decorData.imageUrl !== undefined) payload.image_url = decorData.imageUrl

  const response = await apiClient.patch(`/card/templates/${id}/`, payload)
  const data = response.data?.data || response.data
  return mapBackendHomeDecor(data)
}

export const deleteHomeDecor = async (id: string): Promise<boolean> => {
  await apiClient.delete(`/card/templates/${id}/`)
  return true
}

export const publishHomeDecor = async (id: string): Promise<HomeDecor> => {
  const response = await apiClient.post(`/card/templates/${id}/publish/`)
  const data = response.data?.template || response.data
  return mapBackendHomeDecor(data)
}

export const archiveHomeDecor = async (id: string): Promise<HomeDecor> => {
  const response = await apiClient.post(`/card/templates/${id}/archive/`)
  const data = response.data?.template || response.data
  return mapBackendHomeDecor(data)
}
