import { adminApi } from './client'
import { unwrapItem, unwrapList } from './helpers'
import {
  normalizePage,
  normalizePageBlock,
  normalizePaginated,
} from './normalizers'
import type {
  AdminPageRecord,
  AdminPageBlockRecord,
  ApiItemResponse,
  ApiListResponse,
  PaginatedResult,
} from './types'

export type PagesQuery = {
  page?: number
  perPage?: number
  search?: string
  is_active?: boolean
}

export type PageUpsertPayload = {
  title: string
  slug?: string
  content?: string | null
  meta_title?: string | null
  meta_description?: string | null
  is_active?: boolean
}

export type PageBlockUpsertPayload = {
  type: string
  content: Record<string, unknown>
  order_index?: number
}

export async function fetchPages(
  query: PagesQuery
): Promise<PaginatedResult<AdminPageRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/pages',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        is_active: query.is_active,
      },
    }
  )

  return normalizePaginated(response.data, normalizePage)
}

export async function fetchPage(pageId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/pages/${pageId}`
  )
  return normalizePage(unwrapItem(response))
}

export async function createPage(payload: PageUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/pages', payload)
  return normalizePage(unwrapItem(response))
}

export async function updatePage(
  pageId: number | string,
  payload: PageUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/pages/${pageId}`,
    payload
  )
  return normalizePage(unwrapItem(response))
}

export async function deletePage(pageId: number | string) {
  await adminApi.delete(`/pages/${pageId}`)
}

export async function fetchPageBlocks(
  pageId: number | string
): Promise<AdminPageBlockRecord[]> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    `/pages/${pageId}/blocks`
  )
  return unwrapList(response).map(normalizePageBlock)
}

export async function createPageBlock(
  pageId: number | string,
  payload: PageBlockUpsertPayload
) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >(`/pages/${pageId}/blocks`, payload)
  return normalizePageBlock(unwrapItem(response))
}

export async function updatePageBlock(
  pageId: number | string,
  blockId: number | string,
  payload: PageBlockUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/pages/${pageId}/blocks/${blockId}`,
    payload
  )
  return normalizePageBlock(unwrapItem(response))
}

export async function deletePageBlock(
  pageId: number | string,
  blockId: number | string
) {
  await adminApi.delete(`/pages/${pageId}/blocks/${blockId}`)
}

export async function reorderPageBlocks(
  pageId: number | string,
  items: Array<{ id: number | string; order_index: number }>
) {
  await adminApi.post(`/pages/${pageId}/blocks/reorder`, { items })
}

export type PreviewResponse = {
  token: string
  preview_url: string
  expires_in: number
}

export async function createPreview(
  pageId: number | string,
  blocks: Array<{ type: string; content: Record<string, unknown>; order_index: number }>
): Promise<PreviewResponse> {
  const response = await adminApi.post<PreviewResponse | { data: PreviewResponse }>(
    '/preview',
    { page_id: pageId, blocks }
  )
  const raw = response.data
  return ('token' in raw ? raw : (raw as { data: PreviewResponse }).data) as PreviewResponse
}
