import { useState } from 'react'
import { authClient } from '@/lib/auth'
import { handleError } from './use-error'
import { type ApiError } from '@/lib/types'

export interface ChangePasswordParams {
  oldPassword: string
  newPassword: string
  confirmPassword?: string
}

export interface ChangePasswordResult {
  changePassword: (params: ChangePasswordParams) => Promise<void>
  loading: boolean
  error: ApiError | null
}

export const useChangePassword = (): ChangePasswordResult => {
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<ApiError | null>(null)

  const changePassword = async (params: ChangePasswordParams) => {
    const { oldPassword, newPassword, confirmPassword } = params

    // 客户端验证
    if (!oldPassword) {
      setError({ message: '旧密码不能为空' })
      return
    }

    if (newPassword.length < 6) {
      setError({ message: '新密码长度至少为6位' })
      return
    }

    if (oldPassword === newPassword) {
      setError({ message: '新密码不能与当前密码相同' })
      return
    }

    if (confirmPassword !== undefined && newPassword !== confirmPassword) {
      setError({ message: '新密码和确认密码不一致' })
      return
    }

    try {
      setLoading(true)
      setError(null)

      const result = await handleError(async () => {
        return await authClient.changePassword({
          oldPassword,
          newPassword,
          revokeOtherSessions: true,
        })
      })

      if (result.error) {
        setError(result.error)
      }
    } catch (e) {
      setError(e as ApiError)
    } finally {
      setLoading(false)
    }
  }

  return {
    changePassword,
    loading,
    error,
  }
}
