"use client"

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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { OldDSButton as Button } from "@scandic-hotels/design-system/OldDSButton"
import { toast } from "@scandic-hotels/design-system/Toast"
import { trpc } from "@scandic-hotels/trpc/client"

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({
            defaultMessage: "Your card was successfully saved!",
          })
        )
      })
    } else if (cancel) {
      setTimeout(() => {
        toast.warning(
          intl.formatMessage({
            defaultMessage: "You canceled adding a new credit card.",
          })
        )
      })
    } else if (failure || error) {
      setTimeout(() => {
        toast.error(
          intl.formatMessage({
            defaultMessage:
              "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)
        router.refresh() // / Could be removed on NextJs 15
      } else {
        toast.error(
          intl.formatMessage({
            defaultMessage:
              "We could not add a card right now, please try again later.",
          })
        )
      }
    },
    onError: () => {
      toast.error(
        intl.formatMessage({
          defaultMessage:
            "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
    >
      <MaterialIcon icon="add_circle" color="CurrentColor" />
      {intl.formatMessage({
        defaultMessage: "Add new card",
      })}
    </Button>
  )
}
