import { getQuestions, getCategories, getPatterns } from "@/lib/api";
import type { CategoryListResponse, PatternListResponse, Difficulty } from "@/types";
import { QuestionCard } from "@/components/questions/question-card";
import { QuestionFilters } from "@/components/questions/question-filters";
import { Badge } from "@/components/ui/badge";
import { getDifficultyVariant, capitalize } from "@/lib/utils";
import Link from "next/link";

interface SearchParams {
  difficulty?: string;
  category?: string;
  pattern?: string;
  search?: string;
  page?: string;
}

export default async function QuestionsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const params = await searchParams;
  const [questionsResult, categoriesResult, patternsResult] =
    await Promise.allSettled([
      getQuestions({
        difficulty: params.difficulty,
        category: params.category,
        pattern: params.pattern,
        search: params.search,
        page: params.page ? parseInt(params.page) : 1,
      }),
      getCategories(),
      getPatterns(),
    ]);

  if (questionsResult.status === "rejected") {
    return (
      <div className="space-y-6">
        <h1 className="text-3xl font-bold">Questions</h1>
        <p className="text-[var(--muted-foreground)]">
          Unable to load questions. Please try again later.
        </p>
      </div>
    );
  }

  const questionsResponse = questionsResult.value;
  const categoriesResponse: CategoryListResponse =
    categoriesResult.status === "fulfilled"
      ? categoriesResult.value
      : { items: [] };
  const patternsResponse: PatternListResponse =
    patternsResult.status === "fulfilled"
      ? patternsResult.value
      : { items: [] };

  const difficulties: Difficulty[] = ["easy", "medium", "hard"];

  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold">Questions</h1>

      <div className="flex flex-wrap gap-4 p-4 rounded-lg bg-[var(--secondary)]">
        <div className="space-y-1">
          <label className="text-sm text-[var(--muted-foreground)]">
            Difficulty
          </label>
          <div className="flex gap-2">
            <Link href="/questions">
              <Badge
                variant={!params.difficulty ? "default" : "outline"}
                className="cursor-pointer hover:opacity-80"
              >
                All
              </Badge>
            </Link>
            {difficulties.map((d) => (
              <Link key={d} href={`/questions?difficulty=${d}`}>
                <Badge
                  variant={
                    params.difficulty === d ? getDifficultyVariant(d) : "outline"
                  }
                  className="cursor-pointer hover:opacity-80"
                >
                  {capitalize(d)}
                </Badge>
              </Link>
            ))}
          </div>
        </div>

        <QuestionFilters
          categories={categoriesResponse.items}
          patterns={patternsResponse.items}
          currentCategory={params.category}
          currentPattern={params.pattern}
          currentSearch={params.search}
        />
      </div>

      <div className="text-sm text-[var(--muted-foreground)]">
        Showing {questionsResponse.items.length} of {questionsResponse.total}{" "}
        questions
      </div>

      <div className="grid gap-4">
        {questionsResponse.items.map((question) => (
          <QuestionCard key={question.id} question={question} />
        ))}
      </div>

      {questionsResponse.pages > 1 && (
        <div className="flex justify-center gap-2">
          {Array.from({ length: questionsResponse.pages }, (_, i) => i + 1).map(
            (page) => (
              <Link
                key={page}
                href={`/questions?page=${page}${
                  params.difficulty ? `&difficulty=${params.difficulty}` : ""
                }${params.category ? `&category=${params.category}` : ""}${
                  params.pattern ? `&pattern=${params.pattern}` : ""
                }${params.search ? `&search=${encodeURIComponent(params.search)}` : ""}`}
                className={`px-3 py-1 rounded ${
                  page === questionsResponse.page
                    ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
                    : "bg-[var(--secondary)] hover:bg-[var(--muted)]"
                }`}
              >
                {page}
              </Link>
            )
          )}
        </div>
      )}
    </div>
  );
}
