'use client'

import {
  useGetChargeProductList,
  useGetWalletBalance,
  useGetWebChargeCheckout,
  useGetWebChargePreOrder,
} from '@/hooks/useWallet'
import { Button, IconButton } from '../ui/button'
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
} from '../ui/drawer'
import { useEffect, useState } from 'react'
import { formatFromCents } from '@/utils/number'
import Image from 'next/image'
import { Checkbox } from '../ui/checkbox'
import Link from 'next/link'
import { toast } from 'sonner'
import { Skeleton } from '../ui/skeleton'
import { usePathname, useSearchParams } from 'next/navigation'
import QueryString from 'qs'
import { useAtom } from 'jotai'
import { isChargeDrawerOpenAtom } from '@/atoms/im'
import { useCurrentUser } from '@/hooks/auth'

const ChargeDrawer = () => {
  const [isChargeDrawerOpen, setIsChargeDrawerOpen] = useAtom(isChargeDrawerOpenAtom)
  const [policyCheck, setpolicyCheck] = useState(true)
  const [selectedProductId, setSelectedProductId] = useState<string | null>(null)

  const { data, isLoading } = useGetChargeProductList()
  const { productList } = data || {}
  const pathname = usePathname()
  const searchParams = useSearchParams()

  // 初始化获取钱包余额
  useGetWalletBalance()

  // 支付相关的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 canPay =
    selectedProductId && policyCheck && !preOrderMutation.isPending && !checkoutMutation.isPending

  const handleClose = () => {
    setIsChargeDrawerOpen(false)
  }

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

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

      if (!preOrderResponse.tradeNo) {
        throw new Error('Pre-order failed: No trade number obtained')
      }

      const baseURL = `${process.env.NEXT_PUBLIC_APP_URL}/wallet/charge/result`
      const originalSearch = searchParams.toString()
      const fullPath = originalSearch ? `${pathname}?${originalSearch}` : pathname
      const params = QueryString.stringify({
        redirectURL: fullPath,
        back: 1,
      })
      const returnUrl = `${baseURL}?${params}`
      const cancelUrl = `${baseURL}?${params}`

      // 2. 结账
      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('Failed to get payment link')
      }
    } catch (error) {
      toast.error('Payment failure, please try again')
    }
  }

  const renderList = () => {
    if (isLoading) {
      return (
        <div className="grid grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, index) => (
            <div
              key={index}
              className="bg-surface-nest-normal rounded-m relative flex flex-col items-center justify-center py-6"
            >
              <div className="relative w-full text-center">
                <Skeleton className="bg-surface-nest-normal mx-auto mb-2 h-6 w-16" />
              </div>
              <Skeleton className="bg-surface-nest-normal mt-1 h-4 w-12" />
            </div>
          ))}
        </div>
      )
    }

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

  return (
    <Drawer open={isChargeDrawerOpen} onOpenChange={setIsChargeDrawerOpen} direction="right">
      <DrawerContent>
        <DrawerHeader className="flex items-center gap-2 p-6">
          <IconButton
            iconfont="icon-arrow-right"
            variant="ghost"
            size="small"
            onClick={handleClose}
          />
          <DrawerTitle className="txt-title-m text-txt-primary-normal">Charge</DrawerTitle>
        </DrawerHeader>
        <DrawerDescription className="text-txt-primary-normal px-6">
          The Crush coin is insufficient and cannot continue, please recharge
        </DrawerDescription>
        <div className="px-6">
          <div className="mt-6">{renderList()}</div>

          <div className="mt-6 flex cursor-pointer items-start gap-2">
            {/* <Checkbox shape="round" checked={policyCheck} className="pointer-events-none mt-1" /> */}
            <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>
        <DrawerFooter>
          <div className="flex items-center gap-4">
            <Button variant="tertiary" size="large" className="flex-1" onClick={handleClose}>
              Cancel
            </Button>
            <Button
              onClick={handlePayment}
              disabled={!canPay}
              className="flex-1"
              loading={preOrderMutation.isPending || checkoutMutation.isPending}
            >
              {`Recharge $${selectedProductAmount}`}
            </Button>
          </div>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}

export default ChargeDrawer
