import { useState } from 'react'
import type { ReactNode } from 'react'
import { cn } from '../../lib/utils'
import { motion } from 'framer-motion'
import { IconButton } from '../../basic/icon-button'
import { Button } from '../../basic/button'
import { OptionList } from '../../basic/option-list'
import { Scrollbar } from '../../basic/scrollbar'
import type { OptionItem } from '../../basic/option-list'
import { useUserQuestionContext } from './context'
import type { UserQuestionItem } from './types'

// ===== UserQuestion.Header =====

export interface UserQuestionHeaderProps {
  className?: string
}

export function UserQuestionHeader({ className }: UserQuestionHeaderProps) {
  const ctx = useUserQuestionContext()

  return (
    <div className={cn('flex items-center justify-between mb-2 -mt-2 px-3 pt-2 pb-2 rounded-t-xl bg-fill-tertiary', className)}>
      <div className="flex items-center gap-1.5">
        {ctx.chat4Icon}
        <span className="text-xs leading-xs text-text-tertiary">
          {ctx.currentQuestion?.header || ctx.labels.questionHeader}
        </span>
        <span className="text-text-tertiary/50">•</span>
        <span className="text-xs leading-xs text-text-tertiary">
          {ctx.currentQuestion?.multiSelect ? ctx.labels.multiSelect : ctx.labels.singleSelect}
        </span>
      </div>
      {ctx.questions.length > 1 && (
        <div className="flex items-center gap-1">
          <IconButton
            size="sm"
            variant="ghost"
            onClick={ctx.handlePrevious}
            disabled={ctx.currentQuestionIndex === 0}
            icon={ctx.arrowUpSIcon}
            aria-label="Previous question"
          />
          <span className="text-xs leading-xs text-text-tertiary px-1">
            {ctx.currentQuestionIndex + 1} / {ctx.questions.length}
          </span>
          <IconButton
            size="sm"
            variant="ghost"
            onClick={ctx.handleNext}
            disabled={ctx.currentQuestionIndex === ctx.questions.length - 1}
            icon={ctx.arrowDownSIcon}
            aria-label="Next question"
          />
        </div>
      )}
    </div>
  )
}

UserQuestionHeader.displayName = 'UserQuestionHeader'

// ===== UserQuestion.Card =====

export interface UserQuestionCardProps {
  question: UserQuestionItem
  qIndex: number
  className?: string
}

export function UserQuestionCard({ question, qIndex, className }: UserQuestionCardProps) {
  const ctx = useUserQuestionContext()
  const questionOptions = question.options || []
  const [isInputFocused, setIsInputFocused] = useState(false)
  const hasInputValue = !!(ctx.customInputs[question.question]?.trim())
  const showUnderline = isInputFocused || hasInputValue
  const isCurrentQuestion = qIndex === ctx.currentQuestionIndex

  return (
    <div
      key={question.question}
      ref={(el) => {
        if (el) ctx.questionRefs.current.set(qIndex, el)
        else ctx.questionRefs.current.delete(qIndex)
      }}
      className={cn(
        'transition-opacity duration-200',
        isCurrentQuestion ? 'opacity-100' : 'opacity-40',
        className
      )}
    >
      <div className="flex items-start gap-3 pl-2 mb-3">
        <div className="flex-shrink-0 w-5 flex items-center justify-center text-sm leading-sm font-medium text-text-tertiary">
          {qIndex + 1}.
        </div>
        <div className="text-sm leading-sm font-medium text-text min-w-0 flex-1">
          {question.question}
        </div>
      </div>
      <OptionList
        items={questionOptions.map((opt) => ({
          id: opt.label,
          label: opt.label,
          description: opt.description,
        }))}
        selectedIds={ctx.answers[question.question]?.map((l) => l) || []}
        focusedId={
          isCurrentQuestion ? questionOptions[ctx.focusedOptionIndex]?.label : undefined
        }
        disabled={ctx.isSubmitting || !isCurrentQuestion}
        onItemClick={(item: OptionItem, index: number) => {
          if (!isCurrentQuestion) {
            ctx.setCurrentQuestionIndex(qIndex)
            ctx.setFocusedOptionIndex(ctx.getSelectedOptionIndex(qIndex))
            return
          }
          ctx.handleOptionClick(question.question, item.label, qIndex)
          ctx.setFocusedOptionIndex(index)
        }}
      />
      {question.allowCustomInput !== false && (
        <div
          className={cn(
            'w-full flex gap-3 pl-2 mt-3 transition-colors',
            !isCurrentQuestion && 'opacity-40',
            ctx.isSubmitting && 'opacity-50'
          )}
        >
          <div
            className={cn(
              'flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-xs leading-xs font-medium transition-colors',
              (isCurrentQuestion && ctx.focusedOptionIndex === questionOptions.length) ||
                ctx.customInputs[question.question]?.trim()
                ? 'bg-primary-active text-text-on-primary'
                : 'bg-fill-secondary text-text-tertiary'
            )}
          >
            {questionOptions.length + 1}
          </div>
          <div className="flex-1 min-w-0 flex flex-col">
            <div className="h-5 flex items-center">
              <input
                ref={(el) => {
                  if (el) ctx.customInputRefs.current.set(question.question, el)
                  else ctx.customInputRefs.current.delete(question.question)
                }}
                type="text"
                value={ctx.customInputs[question.question] || ''}
                style={{ outline: 'none', outlineOffset: 0, boxShadow: 'none', border: 'none' }}
                onChange={(e) => {
                  const value = e.target.value
                  ctx.setCustomInputs((prev) => ({ ...prev, [question.question]: value }))
                  if (!question.multiSelect && value.trim()) {
                    ctx.setAnswers((prev) => ({
                      ...prev,
                      [question.question]: [],
                    }))
                  }
                }}
                onFocus={() => {
                  setIsInputFocused(true)
                  if (isCurrentQuestion) {
                    ctx.setFocusedOptionIndex(questionOptions.length)
                    if (!question.multiSelect) {
                      ctx.setAnswers((prev) => ({
                        ...prev,
                        [question.question]: [],
                      }))
                    }
                  }
                }}
                onBlur={() => setIsInputFocused(false)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault()
                    e.stopPropagation()
                    const currentCustomInput = ctx.customInputs[question.question]?.trim()
                    const currentSelectedOptions = ctx.answers[question.question] || []
                    const hasAnswer =
                      currentSelectedOptions.length > 0 || !!currentCustomInput
                    if (hasAnswer) {
                      if (ctx.allQuestionsAnswered) {
                        ctx.handleContinue()
                      } else if (qIndex < ctx.questions.length - 1) {
                        const nextIndex = qIndex + 1
                        ctx.setShouldScrollToQuestion(true)
                        ctx.setCurrentQuestionIndex(nextIndex)
                        ctx.setFocusedOptionIndex(0)
                      } else {
                        ctx.handleContinue()
                      }
                    }
                  }
                }}
                placeholder={ctx.labels.customInputPlaceholder}
                disabled={ctx.isSubmitting || !isCurrentQuestion}
                className={cn(
                  'w-full h-full py-0 bg-transparent text-sm leading-sm font-medium text-text',
                  'placeholder:text-text-tertiary placeholder:font-normal',
                  'border-0 rounded-none outline-none outline-offset-0',
                  'focus:outline-none focus:outline-offset-0',
                  'focus-visible:outline-none focus-visible:outline-offset-0',
                  'ring-0 focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0 shadow-none',
                  'disabled:cursor-not-allowed'
                )}
              />
            </div>
            <div
              className="mt-1.5 overflow-hidden origin-left transition-[width] duration-200 ease-out"
              style={{ width: showUnderline ? '100%' : '0%' }}
              aria-hidden
            >
              <div className="h-px bg-[var(--color-border-tertiary)]" />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

UserQuestionCard.displayName = 'UserQuestionCard'

// ===== UserQuestion.Cards (渲染所有问题卡片) =====

export interface UserQuestionCardsProps {
  className?: string
  children?: ReactNode
}

export function UserQuestionCards({ className, children }: UserQuestionCardsProps) {
  const ctx = useUserQuestionContext()
  // Destructure to avoid lint false positives about ref access during render
  const { scrollContainerRef, maxQuestionHeight, questions } = ctx

  return (
    <Scrollbar
      ref={scrollContainerRef}
      scrollbarVisibility="auto"
      maxHeight={maxQuestionHeight ? maxQuestionHeight : undefined}
      className={cn('scroll-smooth', className)}
    >
      <div className="space-y-4 px-3">
        {children ?? questions.map((question, qIndex) => (
          <UserQuestionCard key={question.question} question={question} qIndex={qIndex} />
        ))}
      </div>
    </Scrollbar>
  )
}

UserQuestionCards.displayName = 'UserQuestionCards'

// ===== UserQuestion.Footer =====

export interface UserQuestionFooterProps {
  className?: string
}

export function UserQuestionFooter({ className }: UserQuestionFooterProps) {
  const ctx = useUserQuestionContext()

  return (
    <div className={cn('flex items-center justify-between px-3 py-2', className)}>
      <Button
        variant="ghost"
        size="sm"
        onClick={ctx.handleRecommend}
        disabled={ctx.isSubmitting}
      >
        {ctx.sparklingIcon}
        {ctx.labels.recommend}
      </Button>
      <div className="flex items-center gap-2">
        {!ctx.allQuestionsAnswered && (
          <Button
            variant="ghost"
            size="sm"
            onClick={ctx.handleSkip}
            disabled={ctx.isSubmitting}
          >
            {ctx.labels.skipAll}
          </Button>
        )}
        <Button
          size="sm"
          variant="secondary"
          onClick={ctx.handleContinue}
          disabled={ctx.isSubmitting || ctx.hasCustomText || !ctx.allQuestionsAnswered}
        >
          {ctx.isSubmitting ? (
            ctx.labels.sending
          ) : (
            <>
              {ctx.allQuestionsAnswered ? ctx.labels.submit : ctx.labels.continue}
              <span className="opacity-70"> ↵</span>
            </>
          )}
        </Button>
      </div>
    </div>
  )
}

UserQuestionFooter.displayName = 'UserQuestionFooter'

// ===== UserQuestion.DefaultLayout =====

export function UserQuestionDefaultLayout() {
  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
      className={cn(
        'border rounded-t-xl border-b-0 border-border border-border-tertiary bg-bg-base overflow-hidden pt-2 pb-2'
      )}
    >
      <UserQuestionHeader />
      <UserQuestionCards />
      <UserQuestionFooter />
    </motion.div>
  )
}

UserQuestionDefaultLayout.displayName = 'UserQuestionDefaultLayout'
