import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
import { useDocument } from "@/context/document/hooks";
import { displayName, relationshipsForDocument } from "@/lib/relationships";
import type { DocumentId } from "@/lib/types";
import { Route as CampaignRoute } from "@/routes/_app/_authenticated/campaigns.$campaignId";
import { Link } from "@tanstack/react-router";
import * as _ from "lodash";
import { Loader } from "../Loader";
import { Route as RelationshipRoute } from "@/routes/_app/_authenticated/document.$documentId/$relationshipType";

export function DocumentView({ documentId }: { documentId: DocumentId }) {
  const { docResult } = useDocument(documentId);

  console.info(`Rendering document: `, docResult);

  if (docResult?.type !== "ready") {
    return <Loader />;
  }

  const doc = docResult.value.doc;
  const relationshipCounts = _.mapValues(docResult.value.relationships, (v) => {
    if (v.type === "ready") {
      return v.value.secondary.length;
    }
    return 0;
  });

  const relationshipList = relationshipsForDocument(doc);

  return (
    <div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
      <div>
        <Link
          to={CampaignRoute.to}
          params={{ campaignId: doc.campaign }}
          className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
        >
          Back to campaign
        </Link>
        <Link
          to="/document/$documentId/print"
          params={{ documentId: doc.id }}
          className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
        >
          Print
        </Link>
      </div>
      <DocumentEditForm document={doc} />
      <nav>
        <ul className="flex flex-row gap-1">
          {relationshipList.map((relationshipType) => (
            <Link
              to={RelationshipRoute.to}
              params={{
                documentId,
                relationshipType,
              }}
            >
              <div
                key={relationshipType}
                className="px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500 data-selected:bg-violet-900 data-selected:border-violet-700 whitespace-nowrap"
              >
                {displayName(relationshipType)} (
                {relationshipCounts[relationshipType] ?? 0})
              </div>
            </Link>
          ))}
        </ul>
      </nav>
    </div>
  );
}
