import { DocumentPrintRow } from "@/components/documents/DocumentPrintRow";
import { SessionPrintRow } from "@/components/documents/session/SessionPrintRow";
import { Loader } from "@/components/Loader";
import { pb } from "@/lib/pocketbase";
import { RelationshipType, type Relationship, type Session } from "@/lib/types";
import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import _ from "lodash";

export const Route = createFileRoute(
  "/_app_/_authenticated/document_/$documentId/print",
)({
  component: RouteComponent,
  pendingComponent: Loader,
});

function RouteComponent() {
  const params = Route.useParams();
  const {
    data: { session, relationships },
  } = useSuspenseQuery({
    queryKey: ["session", "relationships"],
    queryFn: async () => {
      const session = await pb
        .collection("documents")
        .getOne(params.documentId);
      const relationships: Relationship[] = await pb
        .collection("relationships")
        .getFullList({
          filter: `primary = "${params.documentId}"`,
          expand: "secondary",
        });
      console.log("Fetched data: ", relationships);
      return {
        session: session as Session,
        relationships: _.mapValues(
          _.groupBy(relationships, (r) => r.type),
          (rs: Relationship[]) => rs.flatMap((r) => r.expand?.secondary),
        ),
      };
    },
  });

  console.log("Parsed data: ", relationships);

  return (
    <div className="fill-w py-8 columns-2 gap-8 text-sm">
      <SessionPrintRow session={session}></SessionPrintRow>
      {[
        RelationshipType.Scenes,
        RelationshipType.Secrets,
        RelationshipType.Locations,
        RelationshipType.Npcs,
        RelationshipType.Monsters,
        RelationshipType.Treasures,
      ].map((relationshipType) => (
        <div className="break-inside-avoid">
          <h3 className="text-lg font-bold text-slate-600">
            {relationshipType.charAt(0).toUpperCase() +
              relationshipType.slice(1)}
          </h3>

          <ul className="list-disc pl-5">
            {(relationships[relationshipType] ?? []).map((item) => (
              <DocumentPrintRow document={item} />
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}
