'use client'

import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
  useGetChargeProductList,
  useGetWebChargePreOrder,
  useGetWebChargeCheckout,
  useUpdateWalletBalance,
} from '@/hooks/useWallet'
import Image from 'next/image'
import Link from 'next/link'
import { useState, useEffect } from 'react'
import Decimal from 'decimal.js'
import numeral from 'numeral'
import { toast } from 'sonner'
import RechargeListSkeleton from './RechargeListSkeleton'
import { formatFromCents } from '@/utils/number'
import QueryString from 'qs'

const RechargeList = () => {
  const [policyCheck, setpolicyCheck] = useState(true)
  const [selectedProductId, setSelectedProductId] = useState<string | null>(null)

  const { data, isLoading } = useGetChargeProductList()
  const { productList } = data || {}

  // 支付相关的hooks
  const preOrderMutation = useGetWebChargePreOrder()
  const checkoutMutation = useGetWebChargeCheckout()

  // 默认选中第一个产品
  useEffect(() => {
    if (productList && productList.length > 0 && !selectedProductId) {
      setSelectedProductId(productList[0].productId || null)
    }
  }, [productList, selectedProductId])

  const selectedProduct = productList?.find((p) => p.productId === selectedProductId)
  const selectedProductAmount = formatFromCents(selectedProduct?.payAmount || 0, 2)

  // 支付处理函数
  const handlePayment = async () => {
    if (!selectedProductId || !policyCheck) {
      return
    }

    try {
      // 1. 预下单
      const preOrderResponse = await preOrderMutation.mutateAsync({
        productId: selectedProductId,
        version: 1,
      })

      if (!preOrderResponse.tradeNo) {
        throw new Error('预下单失败：未获取到交易号')
      }

      // 2. 结账
      const baseURL = `${process.env.NEXT_PUBLIC_APP_URL}/wallet/charge/result`
      const params = QueryString.stringify({
        redirectURL: '/wallet?back=1',
        back: 1,
      })
      const returnUrl = `${baseURL}?${params}`
      const cancelUrl = `${baseURL}?${params}`
      const checkoutResponse = await checkoutMutation.mutateAsync({
        tradeNo: preOrderResponse.tradeNo,
        payChannel: 'STRIPE',
        returnUrl,
        cancelUrl,
      })

      // 3. 跳转到支付页面
      if (checkoutResponse.paymentUrl) {
        window.location.href = checkoutResponse.paymentUrl
      } else {
        throw new Error('支付链接获取失败')
      }
    } catch (error) {
      toast.error('Payment failure, please try again')
    }
  }

  // 检查是否可以支付
  const canPay =
    selectedProductId && policyCheck && !preOrderMutation.isPending && !checkoutMutation.isPending

  // 显示加载状态
  if (isLoading) {
    return <RechargeListSkeleton />
  }

  return (
    <div>
      <div className="flex flex-col gap-4">
        <h2 className="txt-title-m text-txt-primary-normal">Recharge</h2>

        <div className="grid grid-cols-3 gap-4">
          {productList?.map((product) => {
            const isSelected = selectedProductId === product.productId
            return (
              <div
                key={product.productId}
                className="bg-surface-base-normal rounded-m relative flex cursor-pointer flex-col items-center justify-center p-6 transition-all"
                onClick={() => setSelectedProductId(product.productId || null)}
              >
                {isSelected && (
                  <div className="border-primary-normal absolute -inset-1 rounded-lg border" />
                )}
                <div className="relative text-center">
                  <div className="txt-numDisplay-m">{formatFromCents(product.chargeAmount)}</div>
                  <Image
                    src="/icons/diamond.svg"
                    alt="diamond"
                    className="absolute top-1/2 -left-7 -translate-y-1/2"
                    width={24}
                    height={24}
                  />
                </div>
                <div className="txt-numMonotype-s text-txt-secondary-normal">
                  ${formatFromCents(product.payAmount, 2)}
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* 充值按钮和协议 */}
      <div className="mt-10 flex flex-col items-center gap-3">
        <Button
          onClick={handlePayment}
          disabled={!canPay}
          className={!canPay ? 'cursor-not-allowed opacity-50' : ''}
          loading={preOrderMutation.isPending || checkoutMutation.isPending}
        >
          {`Recharge $${selectedProductAmount}`}
        </Button>
        <div className="flex cursor-pointer items-center gap-2">
          {/* <Checkbox shape="round" checked={policyCheck} className="pointer-events-none" /> */}
          <span className="txt-body-m text-txt-primary-normal">
            By recharging, you agree to the{' '}
            <Link href="/policy/recharge" target="_blank" onClick={(e) => e.stopPropagation()}>
              <span className="text-primary-variant-normal font-medium">
                CrushLevel Recharge Service Agreement
              </span>
            </Link>
          </span>
        </div>
      </div>
    </div>
  )
}

export default RechargeList
