"use client"

import { useCallback, useState } from "react"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import type { InboundPostingFilters, InboundPostingListItem, PaginatedResponse } from "@/types"

function unwrap<T>(value: any): T {
  return value && typeof value === "object" && "data" in value ? value.data : (value as T)
}

export function useInboundPostings() {
  const [items, setItems] = useState<InboundPostingListItem[]>([])
  const [preview, setPreview] = useState<any>(null)
  const [total, setTotal] = useState(0)
  const [pages, setPages] = useState(1)
  const [isLoading, setIsLoading] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const list = useCallback(async (filters: InboundPostingFilters = {}) => {
    setIsLoading(true)
    setError(null)
    try {
      const res = unwrap<PaginatedResponse<InboundPostingListItem>>(await api.get(ENDPOINTS.INBOUND_POSTINGS.LIST, { params: filters }))
      setItems(res.items ?? [])
      setTotal(res.total ?? 0)
      setPages(res.pages ?? 1)
      return res
    } catch (err: any) {
      setError(err?.response?.data?.detail || err?.message || "Failed to load postings")
      return null
    } finally {
      setIsLoading(false)
    }
  }, [])

  const getPreview = useCallback(async (id: string) => {
    setIsLoading(true)
    try {
      const p = unwrap<any>(await api.get(ENDPOINTS.INBOUND_POSTINGS.GET_BY_ID(id)))
      setPreview(p)
      return p
    } catch (err: any) {
      setError(err?.response?.data?.detail || err?.message || "Failed to load preview")
      return null
    } finally {
      setIsLoading(false)
    }
  }, [])

  const act = useCallback(async (id: string, action: string, reason?: string) => {
    const e = ENDPOINTS.INBOUND_POSTINGS
    const endpointMap: Record<string, string> = {
      review: e.REVIEW(id),
      approve: e.APPROVE(id),
      post: e.POST(id),
      reverse: e.REVERSE(id),
      close: e.CLOSE(id),
    }
    const body = action === "reverse" ? { reason: reason || "" } : undefined
    setIsSubmitting(true)
    try {
      return unwrap<any>(await api.post(endpointMap[action], body))
    } finally {
      setIsSubmitting(false)
    }
  }, [])

  return {
    items,
    preview,
    total,
    pages,
    isLoading,
    isSubmitting,
    error,
    list,
    getPreview,
    act,
  }
}
