"use client"

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

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

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

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

import { type AddCreditCardButtonProps } from "@/types/components/myPages/myProfile/addCreditCardButton"

let hasRunOnce = false

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

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

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

    if (success) {
      // setTimeout is used to make sure DOM is loaded before triggering toast. See documentation for more info: https://sonner.emilkowal.ski/toast#render-toast-on-page-load
      setTimeout(() => {
        toast.success(
          intl.formatMessage({ id: "Your card was successfully saved!" })
        )
      })
    } else if (failure) {
      setTimeout(() => {
        toast.error(intl.formatMessage({ id: "Something went wrong!" }))
      })
    }

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

export default function AddCreditCardButton({
  redirectUrl,
}: AddCreditCardButtonProps) {
  const intl = useIntl()
  const router = useRouter()
  const lang = useLang()
  useAddCardResultToast()

  const initiateAddCard = trpc.user.initiateSaveCard.useMutation({
    onSuccess: (result) => (result ? router.push(result.attribute.link) : null),
    onError: () =>
      toast.error(intl.formatMessage({ id: "Something went wrong!" })),
  })

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