'use client'

import { useSearchParams, useRouter } from 'next/navigation'
import { usePaymentPolling } from '@/hooks/usePaymentPolling'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import Image from 'next/image'
import { useQueryClient } from '@tanstack/react-query'
import { walletKeys } from '@/lib/query-keys'

const ResultPage = () => {
  const searchParams = useSearchParams()
  const router = useRouter()
  const submitId = searchParams.get('submitId')
  const redirectURL = searchParams.get('redirectURL')
  const [countdown, setCountdown] = useState(5)
  const queryClient = useQueryClient()

  const { isPolling, pollingData, pollingError, attemptCount, isPaymentSuccess, stopPolling } =
    usePaymentPolling({
      submitId,
      onSuccess: (data) => {
        console.log('支付成功:', data)
        // 这里可以添加支付成功后的逻辑，比如跳转到成功页面
        // router.push('/wallet/charge/success');
      },
      onError: (error) => {
        console.error('支付检查出错:', error)
      },
      onTimeout: () => {
        console.log('支付检查超时')
        // 这里可以添加超时后的逻辑
      },
    })

  // 如果支付成功，可以在这里处理成功逻辑
  useEffect(() => {
    if (isPaymentSuccess && pollingData) {
      // 支付成功，可以跳转或显示成功信息
      queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
    }
  }, [isPaymentSuccess, pollingData])

  // 倒计时逻辑
  useEffect(() => {
    if (isPaymentSuccess && pollingData && countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)

      return () => clearTimeout(timer)
    }

    if (isPaymentSuccess && pollingData && countdown === 0) {
      router.push(redirectURL || '/wallet')
    }
  }, [isPaymentSuccess, pollingData, countdown, router, redirectURL])

  useEffect(() => {
    // 支付页面直接取消返回
    if (!submitId) {
      if (countdown > 0) {
        const timer = setTimeout(() => {
          setCountdown(countdown - 1)
        }, 1000)

        return () => clearTimeout(timer)
      }

      if (countdown === 0) {
        router.push(redirectURL || '/wallet')
      }
    }
  }, [submitId, countdown])

  if (!submitId) {
    return (
      <div className="flex h-full flex-col items-center justify-center">
        <Image src="/images/wallet/icon-pending.png" alt="pending" width={96} height={96} />
        <div className="txt-title-l mt-6">Confirming...</div>
        <div className="txt-body-l mt-4">
          Payment in progress, please do not leave the current page
        </div>
        <Button className="mt-6" variant="tertiary" onClick={() => history.go(-2)}>
          Confirm ({countdown})
        </Button>
      </div>
    )
  }

  if (isPaymentSuccess && pollingData) {
    return (
      <div className="flex h-full flex-col items-center justify-center">
        <Image src="/images/wallet/icon-success.png" alt="pending" width={96} height={96} />
        <div className="txt-title-l mt-6">Success</div>
        <div className="txt-body-l mt-4">Transfer successful. Please check your wallet</div>
        <Button
          className="mt-6"
          variant="tertiary"
          onClick={() => router.push(redirectURL || '/wallet')}
        >
          Confirm ({countdown})
        </Button>
      </div>
    )
  }

  if (pollingError) {
    return (
      <div className="flex h-full flex-col items-center justify-center">
        <Image src="/images/wallet/icon-error.png" alt="pending" width={96} height={96} />
        <div className="txt-title-l mt-6">Something went wrong</div>
      </div>
    )
  }

  return (
    <div className="flex h-full flex-col items-center justify-center">
      <Image src="/images/wallet/icon-pending.png" alt="pending" width={96} height={96} />
      <div className="txt-title-l mt-6">Confirming...</div>
      <div className="txt-body-l mt-4">
        Payment in progress, please do not leave the current page
      </div>
    </div>
  )
}

export default ResultPage
