"use client"

import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { useEffect, useRef } from "react"
import { useIntl } from "react-intl"

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

import { PlusCircleIcon } from "@/components/Icons"
import Button from "@/components/TempDesignSystem/Button"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

import styles from "./addCreditCardButton.module.css"

function useAddCardResultToast() {
  const hasRunOnce = useRef(false)
  const intl = useIntl()
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (hasRunOnce.current) return

    const success = searchParams.get("success")
    const failure = searchParams.get("failure")
    const cancel = searchParams.get("cancel")
    const error = searchParams.get("error")

    if (success) {
      setTimeout(() => {
        toast.success(
          intl.formatMessage({ id: "Your card was successfully saved!" })
        )
      })
    } else if (cancel) {
      setTimeout(() => {
        toast.warning(
          intl.formatMessage({
            id: "You canceled adding a new credit card.",
          })
        )
      })
    } else if (failure || error) {
      setTimeout(() => {
        toast.error(
          intl.formatMessage({
            id: "Something went wrong and we couldn't add your card. Please try again later.",
          })
        )
      })
    }

    router.replace(pathname)
    hasRunOnce.current = true
  }, [intl, pathname, router, searchParams])
}

export default function AddCreditCardButton() {
  const intl = useIntl()
  const router = useRouter()
  const lang = useLang()
  useAddCardResultToast()

  const initiateAddCard = trpc.user.creditCard.add.useMutation({
    onSuccess: (result) => {
      if (result?.attribute.link) {
        router.push(result.attribute.link)
      } else {
        toast.error(
          intl.formatMessage({
            id: "We could not add a card right now, please try again later.",
          })
        )
      }
    },
    onError: () => {
      toast.error(
        intl.formatMessage({
          id: "An error occurred when adding a credit card, please try again later.",
        })
      )
    },
  })

  return (
    <Button
      className={styles.addCreditCardButton}
      variant="icon"
      theme="base"
      intent="text"
      onClick={() =>
        initiateAddCard.mutate({
          language: lang,
        })
      }
      wrapping
    >
      <PlusCircleIcon color="burgundy" />
      {intl.formatMessage({ id: "Add new card" })}
    </Button>
  )
}
