import { useDocument } from "@/context/document/hooks";
import { displayName, relationshipsForDocument } from "@/lib/relationships";
import { RelationshipType, type DocumentId } from "@/lib/types";
import { Route as CampaignRoute } from "@/routes/_app/_authenticated/campaigns.$campaignId";
import { Link } from "@tanstack/react-router";
import _ from "lodash";
import { Loader } from "../Loader";
import { DocumentTitle } from "./DocumentTitle";
import { Tab, TabbedLayout } from "../layout/TabbedLayout";
import { DocumentEditForm } from "./DocumentEditForm";
import { RelatedDocumentList } from "./RelatedDocumentList";
import { DocumentPreview } from "./DocumentPreview";

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();
    }
    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>
          <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 document={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 ? (
          <DocumentEditForm document={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} />;
}
