import { forwardRef } from 'react'
import {
  UserQuestionRootProvider,
  useUserQuestionContext,
  type UserQuestionRootProps,
} from './context'
import {
  UserQuestionHeader,
  UserQuestionCard,
  UserQuestionCards,
  UserQuestionFooter,
  UserQuestionDefaultLayout,
} from './compound'
import type {
  UserQuestionProps,
  UserQuestionHandle,
} from './types'
import { useUserQuestionKeyboard } from './useUserQuestionKeyboard'

export type {
  UserQuestionOption,
  UserQuestionItem,
  UserQuestionLabels,
  UserQuestionProps,
  UserQuestionHandle,
} from './types'
export { DEFAULT_LABELS, NO_PREFERENCE_VALUE } from './types'

// ===== UserQuestion 复合组件类型 =====

export interface UserQuestionCompound {
  Root: React.ForwardRefExoticComponent<UserQuestionRootProps & React.RefAttributes<UserQuestionHandle>>
  Header: typeof UserQuestionHeader
  Card: typeof UserQuestionCard
  Cards: typeof UserQuestionCards
  Footer: typeof UserQuestionFooter
  DefaultLayout: typeof UserQuestionDefaultLayout
}

// ===== 内部键盘处理组件 =====

function KeyboardHandler() {
  const ctx = useUserQuestionContext()
  useUserQuestionKeyboard({
    isSubmitting: ctx.isSubmitting,
    currentQuestion: ctx.currentQuestion,
    currentOptions: ctx.currentOptions,
    currentQuestionIndex: ctx.currentQuestionIndex,
    questions: ctx.questions,
    focusedOptionIndex: ctx.focusedOptionIndex,
    setFocusedOptionIndex: ctx.setFocusedOptionIndex,
    currentQuestionHasAnswer: ctx.currentQuestionHasAnswer,
    getSelectedOptionIndex: ctx.getSelectedOptionIndex,
    setShouldScrollToQuestion: ctx.setShouldScrollToQuestion,
    setCurrentQuestionIndex: ctx.setCurrentQuestionIndex,
    handleOptionClick: ctx.handleOptionClick,
    handleContinue: ctx.handleContinue,
  })
  return null
}

// ===== UserQuestion 便捷组件 =====

const UserQuestionBase = forwardRef<UserQuestionHandle, UserQuestionProps>(
  function UserQuestion(props, ref) {
    return (
      <UserQuestionRootProvider ref={ref} {...props}>
        <KeyboardHandler />
        <UserQuestionDefaultLayout />
      </UserQuestionRootProvider>
    )
  }
)

UserQuestionBase.displayName = 'UserQuestion'

// ===== 挂载复合组件 =====

type UserQuestionBaseType = React.ForwardRefExoticComponent<UserQuestionProps & React.RefAttributes<UserQuestionHandle>> & Partial<UserQuestionCompound>

const UserQuestionWithSlots = UserQuestionBase as UserQuestionBaseType

UserQuestionWithSlots.Root = UserQuestionRootProvider
UserQuestionWithSlots.Header = UserQuestionHeader
UserQuestionWithSlots.Card = UserQuestionCard
UserQuestionWithSlots.Cards = UserQuestionCards
UserQuestionWithSlots.Footer = UserQuestionFooter
UserQuestionWithSlots.DefaultLayout = UserQuestionDefaultLayout

export const UserQuestion = UserQuestionWithSlots as React.ForwardRefExoticComponent<UserQuestionProps & React.RefAttributes<UserQuestionHandle>> &
  UserQuestionCompound

// ===== 导出 Context 和其他工具 =====

export { useUserQuestionContext, UserQuestionDefaultLayout }
