import {
  createContext,
  useState,
  useContext,
  type PropsWithChildren,
  type Dispatch,
  type SetStateAction,
} from 'react'
import { z } from 'zod'

export const uploadCategorySchema = z
  .enum(['featured_image', 'ads', 'content', 'profile_picture'])
  .optional()

export type TUpload = z.infer<typeof uploadCategorySchema>

type AdminContextProperties = {
  isUploadOpen: TUpload
  setIsUploadOpen: Dispatch<SetStateAction<TUpload>>
  uploadedFile?: string
  setUploadedFile: Dispatch<SetStateAction<string | undefined>>
  editProfile: boolean
  setEditProfile: Dispatch<SetStateAction<boolean>>
}

const AdminContext = createContext<AdminContextProperties | undefined>(
  undefined,
)

export const AdminProvider = ({ children }: PropsWithChildren) => {
  const [isUploadOpen, setIsUploadOpen] = useState<TUpload>()
  const [uploadedFile, setUploadedFile] = useState<string | undefined>()
  const [editProfile, setEditProfile] = useState(false)

  return (
    <AdminContext.Provider
      value={{
        isUploadOpen,
        setIsUploadOpen,
        uploadedFile,
        setUploadedFile,
        editProfile,
        setEditProfile,
      }}
    >
      {children}
    </AdminContext.Provider>
  )
}

export const useAdminContext = (): AdminContextProperties => {
  const context = useContext(AdminContext)
  if (!context) {
    throw new Error('useAdminContext must be used within a AdminProvider')
  }
  return context
}
