"use client"

import { useMemo, useState } from "react"

import type { HomeworkAssignmentQuestionAnalytics } from "@/modules/homework/types"
import { HomeworkAssignmentExamPreviewPane } from "@/modules/homework/components/homework-assignment-exam-preview-pane"
import { HomeworkAssignmentQuestionErrorDetailPanel } from "@/modules/homework/components/homework-assignment-question-error-detail-panel"

export function HomeworkAssignmentExamErrorExplorer({
  structure,
  questions,
  gradedSampleCount,
  heightClassName = "h-[560px]",
}: {
  structure: unknown
  questions: HomeworkAssignmentQuestionAnalytics[]
  gradedSampleCount: number
  heightClassName?: string
}) {
  const firstQuestionId = questions[0]?.questionId ?? null
  const [selectedQuestionId, setSelectedQuestionId] = useState<string | null>(firstQuestionId)

  const selected = useMemo(() => {
    if (!selectedQuestionId) return null
    return questions.find((q) => q.questionId === selectedQuestionId) ?? null
  }, [questions, selectedQuestionId])

  return (
    <div className={`grid grid-cols-1 gap-0 md:grid-cols-3 ${heightClassName} divide-y md:divide-y-0 md:divide-x border rounded-md bg-background overflow-hidden`}>
      <HomeworkAssignmentExamPreviewPane
        structure={structure}
        questions={questions.map((q) => ({
          questionId: q.questionId,
          questionType: q.questionType,
          questionContent: q.questionContent,
          maxScore: q.maxScore,
        }))}
        selectedQuestionId={selectedQuestionId}
        onQuestionSelect={setSelectedQuestionId}
      />
      <HomeworkAssignmentQuestionErrorDetailPanel selected={selected} gradedSampleCount={gradedSampleCount} />
    </div>
  )
}
