import { RelationshipList } from "@/components/RelationshipList";
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
import { useDocument } from "@/context/document/DocumentContext";
import { displayName, relationshipsForDocument } from "@/lib/relationships";
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
import { Link } from "@tanstack/react-router";
import { Loader } from "../Loader";

export function DocumentView() {
  const { state } = useDocument();

  if (state.status === "loading") {
    return <Loader />;
  }

  const doc = state.doc;

  const relationshipList = relationshipsForDocument(doc);

  return (
    <div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
      <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>
      <DocumentEditForm document={doc} />
      <TabGroup>
        <TabList className="flex flex-row flex-wrap gap-1 mt-2">
          {relationshipList.map((relationshipType) => (
            <Tab
              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"
            >
              {displayName(relationshipType)}
            </Tab>
          ))}
        </TabList>
        <TabPanels>
          {relationshipList.map((relationshipType) => (
            <TabPanel key={relationshipType}>
              <RelationshipList
                key={relationshipType}
                root={doc}
                relationshipType={relationshipType}
              />
            </TabPanel>
          ))}
        </TabPanels>
      </TabGroup>
    </div>
  );
}
