"use client"

import { createContext, useCallback, useContext, useEffect } from "react"

import { trpc } from "@/lib/trpc/client"

import { getFirstRedeemableCoupon } from "@/utils/rewards"

import type { RedeemFlowContext } from "@/types/components/myPages/myPage/accountPage"
import type { Reward } from "@/types/components/myPages/rewards"

export const RedeemContext = createContext<RedeemFlowContext>({
  redeemStep: "initial",
  setRedeemStep: () => undefined,
  defaultTimeRemaining: 0,
  timeRemaining: 0,
  setTimeRemaining: () => undefined,
})

export default function useRedeemFlow() {
  const {
    redeemStep,
    setRedeemStep,
    defaultTimeRemaining,
    timeRemaining,
    setTimeRemaining,
  } = useContext(RedeemContext)

  const update = trpc.contentstack.rewards.redeem.useMutation<{
    rewards: Reward[]
  }>()

  const onRedeem = useCallback(
    (reward: Reward) => {
      const coupon = getFirstRedeemableCoupon(reward)
      update.mutate(
        { rewardId: reward.id, couponCode: coupon.couponCode },
        {
          onSuccess() {
            setRedeemStep("redeemed")
          },
          onError(error) {
            console.error("Failed to redeem", error)
          },
        }
      )
    },
    [update, setRedeemStep]
  )

  useEffect(() => {
    if (redeemStep === "initial") {
      setTimeRemaining(defaultTimeRemaining)
    }
  }, [redeemStep, setTimeRemaining, defaultTimeRemaining])

  return {
    onRedeem,
    redeemStep,
    setRedeemStep,
    isRedeeming: update.isPending,
    timeRemaining,
    setTimeRemaining,
  }
}
