"use client"

import { createContext, useContext, useState, useEffect, useCallback, useRef } from "react"
import { ICategory, ITicketCategoryContext } from "@/lib/interfaces/ticket/ticket.interface"
import { ApiEndpoint } from "@/lib/services/api.service"
import { getApiErrorMessage, useApi } from "@/lib/services/axios.service"


const TicketCategoryContext = createContext<ITicketCategoryContext | null>(null)

export function useTicketCategoryContext() {
  const ctx = useContext(TicketCategoryContext)
  if (!ctx) {
    throw new Error("useTicketCategoryContext must be used inside TicketCategoryProvider")
  }
  return ctx
}

export function TicketCategoryProvider({ children }: { children: React.ReactNode }) {
  const [categories, setCategories] = useState<ICategory[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [{ loading: apiLoading }, fetchCategoriesApi] = useApi({
    url: ApiEndpoint("ticket", "get"),
    method: "GET"
  })

  const hasFetched = useRef(false)

  const loadCategories = useCallback(async () => {
    if (hasFetched.current) return
    hasFetched.current = true

    setLoading(true)
    setError(null)

    try {
      const response = await fetchCategoriesApi()
      const result = response?.body ?? response

      if (!result?.ok) {
        setError("خطا در دریافت دسته‌بندی‌ها")
        hasFetched.current = false
        return
      }

      setCategories(result.data.categories)
    } catch (err: any) {
      setError(getApiErrorMessage(err))
      hasFetched.current = false
    } finally {
      setLoading(false)
    }
  }, [fetchCategoriesApi])

  return (
    <TicketCategoryContext.Provider value={{
      categories,
      setCategories,
      loadingCategories: loading || apiLoading,
      categoryError: error,
      loadCategories
    }}>
      {children}
    </TicketCategoryContext.Provider>
  )

}
