import _ from "lodash";
import { createFileRoute, Link } from "@tanstack/react-router";
import { pb } from "@/lib/pocketbase";
import {
  RelationshipType,
  type Relationship,
  type Session,
  type Document,
} from "@/lib/types";
import { RelationshipList } from "@/components/RelationshipList";
import { SessionForm } from "@/components/documents/session/SessionForm";

export const Route = createFileRoute(
  "/_app/_authenticated/document/$documentId",
)({
  loader: async ({ params }) => {
    const doc = 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 {
      document: doc,
      relationships: _.mapValues(
        _.groupBy(relationships, (r) => r.type),
        (rs: Relationship[]) => rs.flatMap((r) => r.expand?.secondary),
      ),
    };
  },
  component: RouteComponent,
});

function RouteComponent() {
  const { document: session, relationships } = Route.useLoaderData() as {
    document: Session;
    relationships: Record<RelationshipType, Document[]>;
  };

  async function handleSaveSession(data: Session["data"]) {
    await pb.collection("documents").update(session.id, {
      data,
    });
  }

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

  return (
    <div className="max-w-xl mx-auto py-8">
      <Link
        to="/document/$documentId/print"
        params={{ documentId: session.id }}
        className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
      >
        Print
      </Link>
      <SessionForm session={session as Session} onSubmit={handleSaveSession} />
      {[
        RelationshipType.Scenes,
        RelationshipType.Secrets,
        RelationshipType.Locations,
        RelationshipType.Npcs,
        RelationshipType.Monsters,
        RelationshipType.Treasures,
      ].map((relationshipType) => (
        <RelationshipList
          key={relationshipType}
          root={session}
          relationshipType={relationshipType}
          items={relationships[relationshipType] ?? []}
        />
      ))}
    </div>
  );
}
