import { Suspense } from "react"
import { Plus } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { QuestionDataTable } from "@/modules/questions/components/question-data-table"
import { columns } from "@/modules/questions/components/question-columns"
import { QuestionFilters } from "@/modules/questions/components/question-filters"
import { CreateQuestionButton } from "@/modules/questions/components/create-question-button"
import { MOCK_QUESTIONS } from "@/modules/questions/mock-data"
import { Question } from "@/modules/questions/types"

// Simulate backend delay and filtering
async function getQuestions(searchParams: { [key: string]: string | string[] | undefined }) {
  // In a real app, you would call your DB or API here
  // await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate network latency

  let filtered = [...MOCK_QUESTIONS]

  const q = searchParams.q as string
  const type = searchParams.type as string
  const difficulty = searchParams.difficulty as string

  if (q) {
    filtered = filtered.filter((item) => 
      (typeof item.content === 'string' && item.content.toLowerCase().includes(q.toLowerCase())) ||
      (typeof item.content === 'object' && JSON.stringify(item.content).toLowerCase().includes(q.toLowerCase()))
    )
  }

  if (type && type !== "all") {
    filtered = filtered.filter((item) => item.type === type)
  }

  if (difficulty && difficulty !== "all") {
    filtered = filtered.filter((item) => item.difficulty === parseInt(difficulty))
  }

  return filtered
}

export default async function QuestionBankPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const params = await searchParams
  const questions = await getQuestions(params)

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex flex-col justify-between space-y-4 md:flex-row md:items-center md:space-y-0">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">Question Bank</h2>
          <p className="text-muted-foreground">
            Manage your question repository for exams and assignments.
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <CreateQuestionButton />
        </div>
      </div>

      <div className="space-y-4">
        <Suspense fallback={<div className="h-10 w-full animate-pulse rounded-md bg-muted" />}>
           <QuestionFilters />
        </Suspense>
        
        <div className="rounded-md border bg-card">
          <QuestionDataTable columns={columns} data={questions} />
        </div>
      </div>
    </div>
  )
}
