import type { TocItem } from "@/components/lab-remark/extract-toc";
import { useLabInstanceContext } from "@/components/labs/lab-instance-context";
import type { ParsedSection } from "@/components/labs/parse-section";
import { NextLink } from "@/components/next-link";
import type { LabInstanceMeta } from "@/lib/api/labs.v2";
import { cn } from "@/lib/utils";
import { usePathname } from "next/navigation";

export function LabNavV2({ preview = false }: { preview?: boolean }) {
  const { parsedSections: sections = [], step } = useLabInstanceContext();
  return (
    <div className="w-full text-sm text-muted-foreground bg-background space-y-2">
      {sections.map((section, index) => (
        <div key={index}>
          <LabNavModule
            step={index}
            active={index === step}
            preview={preview}
            section={section}
          />
          <div className="pl-2">
            {section.toc.map((item) => (
              <LabNavChapter
                key={item.id}
                step={index}
                toc={item}
                preview={preview}
                isPublic={section.isVisible}
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function LabNavModule({
  section,
  active,
  step,
  preview,
}: {
  section: ParsedSection;
  active: boolean;
  step: number;
  preview: boolean;
}) {
  const pathname = usePathname();
  const { lab } = useLabInstanceContext();

  if (active) {
    return <div className="font-semibold text-primary">{section.title}</div>;
  } else if (section.isVisible) {
    return (
      <NextLink
        noStyle
        href={getStepUrl(pathname, lab, preview, step)}
        className="font-semibold"
      >
        {section.title}
      </NextLink>
    );
  } else {
    return <div className="font-semibold opacity-50">{section.title}</div>;
  }
}

function LabNavChapter({
  toc,
  isPublic,
  step,
  preview,
}: {
  toc: TocItem;
  isPublic: boolean;
  step: number;
  preview: boolean;
}) {
  const pathname = usePathname();
  const { lab } = useLabInstanceContext();

  if (isPublic) {
    return (
      <NextLink
        noStyle
        href={getStepUrl(pathname, lab, preview, step, toc.id)}
        className={cn("block text-wrap", toc.level === 4 ? "pl-1" : "")}
      >
        {toc.title}
      </NextLink>
    );
  } else {
    return (
      <div
        className={cn(
          "block text-wrap opacity-50",
          toc.level === 4 ? "pl-1" : ""
        )}
      >
        {toc.title}
      </div>
    );
  }
}

function getStepUrl(
  pathname: string,
  lab: LabInstanceMeta,
  preview: boolean,
  step: number,
  hash?: string
) {
  let url = pathname;
  if (preview) {
    url += `?preview=${lab.lab_code}`;
  } else {
    url += `?instance=${lab.id}`;
  }
  if (step > 0) {
    url += `&step=${step}`;
  }
  if (hash) {
    url += `#${hash}`;
  }

  return url;
}
