import { useDocument } from "@/context/document/hooks";
import { displayName, relationshipsForDocument } from "@/lib/relationships";
import { RelationshipType, type DocumentId } from "@/lib/types";
import { Link } from "@tanstack/react-router";
import _ from "lodash";
import { Tab, TabbedLayout } from "../layout/TabbedLayout";
import { Loader } from "../Loader";
import { DocumentPreview } from "./DocumentPreview";
import { DocumentTitle } from "./DocumentTitle";
import { GenericEditForm } from "./GenericEditForm";
import { RelatedDocumentList } from "./RelatedDocumentList";

export function DocumentView({
  documentId,
  relationshipType,
  childDocId,
}: {
  documentId: DocumentId;
  relationshipType: RelationshipType | null;
  childDocId: DocumentId | null;
}) {
  const { docResult } = useDocument(documentId);

  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.toString();
    }
    if (v.type === "empty") {
      return "0";
    }
    return "...";
  });

  const relationshipList = relationshipsForDocument(doc);

  return (
    <TabbedLayout
      navigation={
        <>
          <Link
            to="/campaigns/$campaignId"
            params={{ campaignId: doc.campaign }}
            search={{ tab: "sessions" }}
            className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors"
          >
            ← Back to campaign
          </Link>
          {/* Print link isn't currently working */}
          {/* <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" */}
          {/* > */}
          {/*   Print */}
          {/* </Link> */}
        </>
      }
      title={<DocumentTitle doc={doc} />}
      tabs={[
        <Tab
          to="/document/$documentId"
          key="attributes"
          params={{
            documentId,
          }}
          label="Attributes"
          active={relationshipType === null}
        />,
        ...relationshipList.map((relationshipEntry) => (
          <Tab
            to="/document/$documentId/$relationshipType"
            key={relationshipEntry}
            params={{
              documentId,
              relationshipType: relationshipEntry,
            }}
            label={`${displayName(relationshipEntry)} (${relationshipCounts[relationshipEntry] ?? 0})`}
            active={relationshipEntry === relationshipType}
          />
        )),
      ]}
      content={
        relationshipType === null ? (
          <GenericEditForm doc={doc} />
        ) : (
          <RelatedDocumentList
            documentId={doc.id}
            relationshipType={relationshipType}
          />
        )
      }
      flyout={childDocId && <Flyout key={childDocId} docId={childDocId} />}
    />
  );
}

function Flyout({ docId }: { docId: DocumentId }) {
  const { docResult } = useDocument(docId);

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

  const doc = docResult.value.doc;

  return <DocumentPreview doc={doc} />;
}
