'use client'
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from '@/components/ui/dialog'
import {Button} from '@/components/ui/button'
import balance from './_assets/balance.svg'
import Image from 'next/image'
import {useState} from 'react'
import {useProfileStore} from '@/components/stores-provider'
import {Alert, AlertTitle} from '@/components/ui/alert'
import {toast} from 'sonner'
import {useRouter} from 'next/navigation'
import {completeResource, createResource, prepareResource} from '@/actions/resource'
import {PaymentMethod, Platform, usePlatformType} from '@/lib/models/trade'
import {PaymentModal} from '@/components/composites/payment/payment-modal'
import type {Trade} from '@/components/composites/payment/types'

export type PayProps = {
  method: 'alipay' | 'wechat' | 'balance'
  amount: string
  resource: Parameters<typeof createResource>[0]
}

export default function Pay(props: PayProps) {
  const profile = useProfileStore(store => store.profile)
  const refreshProfile = useProfileStore(store => store.refreshProfile)
  const [open, setOpen] = useState(false)
  const [trade, setTrade] = useState<Trade | null>(null)
  const router = useRouter()
  const platform = usePlatformType()

  const onOpen = async () => {
    setOpen(true)

    if (props.method === 'balance') return

    // 准备支付信息
    const paymentMethod = props.method === 'alipay'
      ? platform === Platform.Mobile
        ? PaymentMethod.SftAlipay // 4
        : PaymentMethod.Alipay // 1
      : platform === Platform.Mobile
        ? PaymentMethod.SftWeChat // 5
        : PaymentMethod.WeChat // 2

    const res = {
      ...props.resource,
      payment_method: paymentMethod,
      payment_platform: platform,
    }
    console.log(res, '请求参数')

    const resp = await prepareResource(res)
    if (!resp.success) {
      toast.error(`创建订单失败: ${resp.message}`)
      setOpen(false)
      return
    }

    setTrade({
      inner_no: resp.data.trade_no,
      method: props.method === 'alipay' ? PaymentMethod.Alipay : PaymentMethod.WeChat,
      pay_url: resp.data.pay_url,
      amount: Number(props.amount),
    })
  }

  const onSubmit = async () => {
    try {
      let resp: Awaited<ReturnType<typeof completeResource>> | Awaited<ReturnType<typeof createResource>>

      if (props.method === 'balance') {
        resp = await createResource(props.resource)
      }
      else if (trade) {
        resp = await completeResource({trade_no: trade.inner_no})
      }
      else {
        throw new Error('支付信息不存在')
      }

      if (!resp.success) throw new Error(resp.message)

      toast.success('购买成功', {
        action: {
          label: '去提取',
          onClick: () => router.push('/admin/extract'),
        },
      })

      setOpen(false)
      await refreshProfile()
    }
    catch (e) {
      toast.error('购买失败', {
        description: (e as Error).message,
      })
    }
  }

  const balanceEnough = profile && profile.balance >= Number(props.amount)

  return (
    <>
      <Button className="mt-4 h-12" onClick={onOpen}>
        立即支付
      </Button>

      {/* 余额支付对话框 */}
      {/* 余额支付对话框 */}
      {props.method === 'balance' && (
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle className="flex gap-2 items-center">
                <Image src={balance} alt="余额" width={20} height={20}/>
                <span>余额支付</span>
              </DialogTitle>
            </DialogHeader>

            {profile && (
              <div className="flex flex-col gap-4">
                <div className="flex flex-col gap-1">
                  <div className="flex justify-between items-center">
                    <span className="text-weak text-sm">账户余额</span>
                    <span className="text-lg">
                      {profile.balance}
                      元
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-weak text-sm">支付金额</span>
                    <span className="text-lg text-accent">
                      -
                      {props.amount}
                      元
                    </span>
                  </div>
                  <hr className="my-2"/>
                  <div className="flex justify-between items-center">
                    <span className="text-weak text-sm">支付后余额</span>
                    <span className={`text-lg ${balanceEnough ? 'text-done' : 'text-fail'}`}>
                      {(profile.balance - Number(props.amount)).toFixed(2)}
                      元
                    </span>
                  </div>
                </div>

                {balanceEnough ? (
                  <Alert variant="done">
                    <AlertTitle>
                      检查无误后，点击确认支付按钮完成支付
                    </AlertTitle>
                  </Alert>
                ) : (
                  <Alert variant="fail">
                    <AlertTitle>
                      余额不足，请先充值或选择其他支付方式
                    </AlertTitle>
                  </Alert>
                )}
              </div>
            )}

            <DialogFooter>
              <Button
                disabled={!balanceEnough}
                onClick={onSubmit}
              >
                确认支付
              </Button>
              <Button theme="outline" onClick={() => setOpen(false)}>
                取消
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {/* 支付宝/微信支付使用公共组件 */}
      {props.method !== 'balance' && trade && (
        <PaymentModal
          open={open}
          onOpenChange={setOpen}
          trade={trade}
          platform={platform}
          onSuccess={onSubmit}
        />
      )}
    </>
  )
}
