import { memo } from 'react'
import type { ReactNode } from 'react'
import { QuestionAnswerLine } from '../basic/icons-inline'

export interface UserQuestionAnswerLabels {
  answer?: string
  answers?: string
}

export interface UserQuestionAnswerProps {
  answers: Record<string, string>
  showHeader?: boolean
  labels?: UserQuestionAnswerLabels
  className?: string
  questionAnswerIcon?: ReactNode
}

const DEFAULT_LABELS: Required<UserQuestionAnswerLabels> = {
  answer: 'Answer',
  answers: 'Answers',
}

const iconClass = 'w-4 h-4 shrink-0 text-text-tertiary'

export const UserQuestionAnswer = memo(function UserQuestionAnswer({
  answers,
  showHeader = true,
  labels: labelsProp,
  className = '',
  questionAnswerIcon,
}: UserQuestionAnswerProps) {
  const labels = { ...DEFAULT_LABELS, ...labelsProp }
  const entries = Object.entries(answers)
  const defaultIcon = questionAnswerIcon ?? <QuestionAnswerLine className={iconClass} />

  if (entries.length === 0) return null

  return (
    <div
      className={`rounded-lg border border-border-tertiary bg-bg-container overflow-hidden mx-2 ${className}`.trim()}
    >
      {showHeader && (
        <div className="flex items-center gap-2 pl-3 pr-3 h-8 border-b border-border-tertiary">
          {defaultIcon}
          <span className="text-xs leading-xs text-text-tertiary">
            {entries.length === 1 ? labels.answer : labels.answers}
          </span>
        </div>
      )}
      <div className="flex flex-col gap-3 p-3 text-xs leading-xs">
        {entries.map(([question, answer], idx) => (
          <div key={idx} className="flex flex-col gap-1">
            <span className="font-medium text-text">{question}</span>
            <span className="text-text-tertiary">{answer}</span>
          </div>
        ))}
      </div>
    </div>
  )
})

UserQuestionAnswer.displayName = 'UserQuestionAnswer'
