import { getQuestion } from "@/lib/api";
import { Badge } from "@/components/ui/badge";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { CodeBlock } from "@/components/ui/code-block";
import { Markdown } from "@/components/ui/markdown";
import { Callout, ApproachBox } from "@/components/ui/callout";
import { Collapsible } from "@/components/ui/collapsible";
import { getDifficultyVariant, getDifficultyLabel, capitalize } from "@/lib/utils";
import {
  FileText,
  AlertCircle,
  BookOpen,
  Code,
  Clock,
  HardDrive,
} from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";

export default async function QuestionDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;

  let question;
  try {
    question = await getQuestion(slug);
  } catch {
    notFound();
  }

  const optimalSolutions = question.solutions.filter((s) => s.is_optimal);
  const otherSolutions = question.solutions.filter((s) => !s.is_optimal);

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      <div>
        <div className="flex items-start justify-between gap-4 mb-4">
          <h1 className="text-3xl font-bold">{question.title}</h1>
          <Badge
            variant={getDifficultyVariant(question.difficulty)}
            aria-label={getDifficultyLabel(question.difficulty)}
          >
            {capitalize(question.difficulty)}
          </Badge>
        </div>

        <div className="flex flex-wrap gap-2 mb-4">
          {question.categories.map((cat) => (
            <Link key={cat.id} href={`/questions?category=${cat.slug}`}>
              <Badge variant="category">{cat.name}</Badge>
            </Link>
          ))}
          {question.patterns.map((pat) => (
            <Link key={pat.id} href={`/patterns/${pat.slug}`}>
              <Badge variant="pattern">{pat.name}</Badge>
            </Link>
          ))}
        </div>

        {question.leetcode_url && (
          <a
            href={question.leetcode_url}
            target="_blank"
            rel="noopener noreferrer"
            aria-label={`View ${question.title} on LeetCode (opens in new tab)`}
            className="text-[var(--primary)] hover:underline text-sm"
          >
            View on LeetCode
          </a>
        )}
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5" aria-hidden="true" />
            Problem
          </CardTitle>
        </CardHeader>
        <CardContent className="prose-content">
          <Markdown>{question.description}</Markdown>
        </CardContent>
      </Card>

      {question.constraints && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5" aria-hidden="true" />
              Constraints
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Markdown>{question.constraints}</Markdown>
          </CardContent>
        </Card>
      )}

      {question.examples && question.examples.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BookOpen className="h-5 w-5" aria-hidden="true" />
              Examples
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {question.examples.map((example, i) => (
              <div
                key={i}
                className="p-4 rounded bg-[var(--secondary)] space-y-2"
              >
                <div>
                  <span className="font-medium">Input: </span>
                  <code>{example.input}</code>
                </div>
                <div>
                  <span className="font-medium">Output: </span>
                  <code>{example.output}</code>
                </div>
                {example.explanation && (
                  <div className="text-sm text-[var(--muted-foreground)]">
                    {example.explanation}
                  </div>
                )}
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      {question.explanation && (
        <>
          <Callout variant="info" title="Approach">
            <div className="prose-content">
              <Markdown>{question.explanation.approach}</Markdown>
            </div>
          </Callout>

          <Callout variant="insight" title="Intuition">
            <div className="prose-content">
              <Markdown>{question.explanation.intuition}</Markdown>
            </div>
          </Callout>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5" aria-hidden="true" />
                Complexity Analysis
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-start gap-2">
                <Clock
                  className="h-4 w-4 mt-1 text-[var(--muted-foreground)]"
                  aria-hidden="true"
                />
                <div className="[&>div]:inline [&>div>p]:inline">
                  <span className="font-medium">Time Complexity: </span>
                  <Markdown>{question.explanation.time_complexity}</Markdown>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <HardDrive
                  className="h-4 w-4 mt-1 text-[var(--muted-foreground)]"
                  aria-hidden="true"
                />
                <div className="[&>div]:inline [&>div>p]:inline">
                  <span className="font-medium">Space Complexity: </span>
                  <Markdown>{question.explanation.space_complexity}</Markdown>
                </div>
              </div>
            </CardContent>
          </Card>

          {question.explanation.common_pitfalls &&
            question.explanation.common_pitfalls.length > 0 && (
              <Callout variant="warning" title="Common Pitfalls">
                <div className="space-y-4">
                  {question.explanation.common_pitfalls.map((pitfall, i) => (
                    <div key={i}>
                      <h4 className="font-medium mb-2">{pitfall.title}</h4>
                      <div className="text-sm prose-content mb-3">
                        <Markdown>{pitfall.description}</Markdown>
                      </div>
                      {(pitfall.wrong_approach || pitfall.correct_approach) && (
                        <div className="space-y-2">
                          {pitfall.wrong_approach && (
                            <ApproachBox variant="wrong">
                              <code className="text-sm">
                                {pitfall.wrong_approach}
                              </code>
                            </ApproachBox>
                          )}
                          {pitfall.correct_approach && (
                            <ApproachBox variant="correct">
                              <code className="text-sm">
                                {pitfall.correct_approach}
                              </code>
                            </ApproachBox>
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </Callout>
            )}

          {question.explanation.key_takeaways &&
            question.explanation.key_takeaways.length > 0 && (
              <Callout variant="success" title="Key Takeaways">
                <ul className="list-disc list-inside space-y-2">
                  {question.explanation.key_takeaways.map((takeaway, i) => (
                    <li key={i} className="[&>div]:inline [&>div>p]:inline">
                      <Markdown>{takeaway}</Markdown>
                    </li>
                  ))}
                </ul>
              </Callout>
            )}
        </>
      )}

      {question.solutions.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Code className="h-5 w-5" aria-hidden="true" />
              Solutions
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {optimalSolutions.map((solution) => (
              <div key={solution.id}>
                <div className="flex items-center gap-2 mb-2">
                  <h4 className="font-medium">{solution.approach_name}</h4>
                  <Badge variant="optimal">Optimal</Badge>
                </div>
                {solution.explanation && (
                  <div className="text-sm text-[var(--muted-foreground)] mb-3 prose-content">
                    <Markdown>{solution.explanation}</Markdown>
                  </div>
                )}
                <CodeBlock code={solution.code} language={solution.language} />
              </div>
            ))}

            {otherSolutions.length > 0 && (
              <div className="space-y-4">
                {otherSolutions.map((solution) => (
                  <Collapsible
                    key={solution.id}
                    title={
                      <span className="flex items-center gap-2">
                        {solution.approach_name}
                        <Badge
                          variant="outline"
                          className="text-xs font-normal"
                        >
                          Alternative
                        </Badge>
                      </span>
                    }
                    defaultOpen={false}
                  >
                    {solution.explanation && (
                      <div className="text-sm text-[var(--muted-foreground)] mb-3 prose-content">
                        <Markdown>{solution.explanation}</Markdown>
                      </div>
                    )}
                    <CodeBlock
                      code={solution.code}
                      language={solution.language}
                    />
                  </Collapsible>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
