import { useRef, useState } from "react";

import { useProjectWorkspace } from "@/hooks/workspace/use-project-workspace";
import { useVisualViewportStyle } from "@/hooks/workspace/use-visual-viewport";
import { findSourceMessageTarget } from "@/lib/workspace/presentation";

import { ConversationComposer } from "./conversation-composer";
import { ConversationFeed } from "./conversation-feed";
import { ProjectConnectForm } from "./project-connect-form";
import { ProjectHeader } from "./project-header";
import { WorkFeed } from "./work-feed";

const ProjectLoading = () => (
  <main className="grid min-h-svh place-items-center bg-[#f2f0e7]">
    <span className="size-5 animate-spin rounded-full border-2 border-[#20201d] border-t-transparent" />
  </main>
);

export const ProjectWorkspacePage = () => {
  const workspace = useProjectWorkspace();
  const viewportStyle = useVisualViewportStyle();
  const [draft, setDraft] = useState("");
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [highlightedMessageId, setHighlightedMessageId] = useState<string>();
  const highlightTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  if (workspace.projects === undefined) {
    return <ProjectLoading />;
  }
  if (!workspace.selectedProject) {
    return <ProjectConnectForm workspace={workspace} />;
  }

  const works = workspace.works ?? [];
  const revealSourceMessage = (rawText: string) => {
    const messageId = findSourceMessageTarget(
      workspace.agent.messages,
      rawText
    );
    if (!messageId) {
      return;
    }
    setDrawerOpen(false);
    setHighlightedMessageId(messageId);
    if (highlightTimer.current) {
      clearTimeout(highlightTimer.current);
    }
    requestAnimationFrame(() =>
      document
        .querySelector(`#workspace-message-${CSS.escape(messageId)}`)
        ?.scrollIntoView({ behavior: "smooth", block: "center" })
    );
    highlightTimer.current = setTimeout(
      () => setHighlightedMessageId(undefined),
      1800
    );
  };

  return (
    <main
      className="workspace-surface fixed inset-x-0 top-0 flex min-h-0 overflow-hidden bg-[#f2f0e7] text-[#20201d]"
      style={viewportStyle}
    >
      <section className="flex min-w-0 flex-1 flex-col">
        <ProjectHeader
          onOpenDrawer={() => setDrawerOpen(true)}
          workspace={workspace}
        />
        <ConversationFeed
          highlightedMessageId={highlightedMessageId}
          onSourceSelect={revealSourceMessage}
          workspace={workspace}
        />
        <ConversationComposer
          draft={draft}
          onDraftChange={setDraft}
          workspace={workspace}
        />
      </section>
      <aside className="hidden w-[380px] shrink-0 overflow-y-auto border-l border-[#d7d3c7] bg-[#e9e7de] p-4 lg:block">
        <h2 className="text-sm font-semibold">Proposed Work</h2>
        <p className="mb-4 text-xs text-[#747168]">
          {works.length} durable outcomes
        </p>
        <WorkFeed
          onSourceSelect={revealSourceMessage}
          works={works}
          workspace={workspace}
        />
      </aside>
      {drawerOpen ? (
        <div className="fixed inset-0 z-50 bg-black/30 lg:hidden">
          <button
            aria-label="Close Work drawer"
            className="absolute inset-0"
            onClick={() => setDrawerOpen(false)}
            type="button"
          />
          <section className="absolute inset-y-0 right-0 flex w-[min(92vw,380px)] flex-col bg-[#e9e7de] shadow-2xl">
            <header className="flex h-14 items-center border-b border-[#cfcbc0] px-4">
              <h2 className="flex-1 text-sm font-semibold">Proposed Work</h2>
              <button
                aria-label="Close Work drawer"
                className="grid size-9 place-items-center"
                onClick={() => setDrawerOpen(false)}
                type="button"
              >
                ×
              </button>
            </header>
            <div className="flex-1 overflow-y-auto p-4">
              <WorkFeed
                onSourceSelect={revealSourceMessage}
                works={works}
                workspace={workspace}
              />
            </div>
          </section>
        </div>
      ) : null}
    </main>
  );
};
