'use client'
import {ChangePasswordDialog} from '@/components/composites/dialogs/change-password-dialog'
import {RealnameAuthDialog} from '@/components/composites/dialogs/realname-auth-dialog'
import {useState, useEffect} from 'react'
import {User} from '@/lib/models'

export function PasswordSetupWrapper({profile}: {profile: User}) {
  const [showPasswordDialog, setShowPasswordDialog] = useState(false)
  const [showRealnameDialog, setShowRealnameDialog] = useState(false)

  useEffect(() => {
    // 每次profile变化时都检查是否需要显示弹窗
    if (!profile.has_password) {
      setShowPasswordDialog(true)
    }
    else if (!profile.id_token) {
      setShowRealnameDialog(true)
    }
  }, [profile.has_password, profile.id_token])

  const handleDismiss = (type: 'password' | 'realname') => {
    // 可选：使用sessionStorage只在当前会话期间记住关闭状态
    if (typeof window !== 'undefined') {
      sessionStorage.setItem(`dismissed${type === 'password' ? 'PasswordSetup' : 'RealnameAuth'}`, 'true')
    }
  }

  return (
    <>
      {showPasswordDialog && (
        <ChangePasswordDialog
          triggerClassName="hidden"
          open={showPasswordDialog}
          onOpenChange={(open) => {
            setShowPasswordDialog(open)
            if (!open) {
              handleDismiss('password')
              if (!profile.id_token) {
                setShowRealnameDialog(true)
              }
            }
          }}
          onSuccess={() => {
            setShowPasswordDialog(false)
            if (!profile.id_token) {
              setShowRealnameDialog(true)
            }
          }}
        />
      )}

      {showRealnameDialog && (
        <RealnameAuthDialog
          hasAuthenticated={!!profile.id_token}
          triggerClassName="hidden"
          open={showRealnameDialog}
          onOpenChange={(open) => {
            setShowRealnameDialog(open)
            if (!open) {
              handleDismiss('realname')
            }
          }}
          onSuccess={() => {
            setShowRealnameDialog(false)
          }}
        />
      )}
    </>
  )
}
