import Link from "next/link";

import {Badge} from "@/components/ui/badge";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {ScrollArea} from "@/components/ui/scroll-area";
import {cn} from "@/lib/utils";

type ChapterItem = {
  _key: string;
  title: string;
  slug: string;
  status: "draft" | "inReview" | "published" | "hidden";
};

type Props = {
  chapters: ChapterItem[];
  activeChapterKey: string;
  resourceSlug: string;
  previewEnabled: boolean;
};

export function ChapterSidebarNav({chapters, activeChapterKey, resourceSlug, previewEnabled}: Props) {
  return (
    <Card className="sticky top-6">
      <CardHeader className="pb-3">
        <CardTitle className="text-sm uppercase tracking-wide text-muted-foreground">Chapters</CardTitle>
      </CardHeader>
      <CardContent className="p-0">
        <ScrollArea className="h-[60vh] px-3 pb-3">
          <nav className="space-y-2">
            {chapters.map((chapter, index) => {
              const isActive = chapter._key === activeChapterKey;
              return (
                <Link
                  key={chapter._key}
                  href={`/resources/${resourceSlug}?chapter=${chapter.slug}`}
                  className={cn(
                    "block rounded-lg border px-3 py-2.5 text-sm transition",
                    isActive
                      ? "border-primary bg-primary text-primary-foreground"
                      : "border-border bg-card text-card-foreground hover:border-primary/30 hover:bg-muted",
                  )}
                >
                  <span className="font-medium">
                    {index + 1}. {chapter.title}
                  </span>
                  {previewEnabled ? (
                    <span className="ml-2 inline-flex align-middle">
                      <Badge variant="outline" className="text-[11px] uppercase">
                        {chapter.status}
                      </Badge>
                    </span>
                  ) : null}
                </Link>
              );
            })}
          </nav>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
