'use client'
import {MobilePayment} from './mobile-payment'
import {DesktopPayment} from './desktop-payment'
import {TradePlatform} from '@/lib/models/trade'
import {Dialog} from '@/components/ui/dialog'
import {PaymentProps} from './type'
import {payClose} from '@/actions/resource'
import {useEffect} from 'react'
import {UniversalDesktopPayment} from './universal-desktop-payment'

export type PaymentModalProps = {
  onConfirm: (showFail: boolean) => Promise<void>
  onClose: () => void
} & PaymentProps

export function PaymentModal(props: PaymentModalProps) {
  // 手动关闭时的处理
  const handleClose = async () => {
    try {
      const res = await payClose({
        trade_no: props.inner_no,
        method: props.method,
      })
      if (!res.success) {
        throw new Error(res.message)
      }
    }
    catch (error) {
      console.error('关闭订单失败:', error)
    }
    finally {
      props.onClose?.()
    }
  }

  // SSE处理方式检查支付状态
  useEffect(() => {
    const eventSource = new EventSource(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/trade/check?trade_no=${props.inner_no}&method=${props.method}`,
    )
    eventSource.onmessage = async (event) => {
      switch (event.data) {
      case '1':
        props.onConfirm?.(true)
      case '2':
        props.onClose?.()
      }
    }
    eventSource.onerror = (error) => {
      console.error('SSE 连接错误:', error)
    }

    return () => {
      eventSource.close()
    }
  }, [props])

  return (
    <Dialog
      defaultOpen={true}
      onOpenChange={(open) => {
        if (!open) handleClose()
      }}>

      {/* {props.platform === TradePlatform.Mobile
        ? <MobilePayment {...props} onClose={handleClose}/>
        : <DesktopPayment {...props} onClose={handleClose}/>
      } */}

      <UniversalDesktopPayment {...props} onClose={handleClose}/>
    </Dialog>
  )
}
