import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import type {
  MobileAssistantMessageView,
  MobileAssistantView,
} from "@code/ui/components/mobile-product";
import { useQuery } from "convex/react";

import { useOrganizationChatAgent } from "@/hooks/chat/use-chat-agent";
import { usePersonalOrganization } from "@/hooks/use-personal-organization";
import { useProjectWorkspace } from "@/hooks/use-project-workspace";
import { STATUS_COPY } from "@/lib/chat/constants";
import { getMessageText } from "@/lib/chat/transforms";
import { buildMobileWorkspaceView } from "@/lib/mobile-workspace/build-mobile-workspace-view";

const toAssistantMessages = (
  messages: ReturnType<typeof useOrganizationChatAgent>["messages"]
): MobileAssistantMessageView[] =>
  messages.flatMap((message) => {
    if (message.role !== "assistant" && message.role !== "user") {
      return [];
    }
    const text = getMessageText(message);
    return text
      ? [
          {
            id: message.id,
            role: message.role,
            text,
          },
        ]
      : [];
  });

const getStatusTone = (
  status: ReturnType<typeof useOrganizationChatAgent>["status"]
): MobileAssistantView["statusTone"] => {
  if (status === "error") {
    return "red";
  }
  return status === "connecting" ? "amber" : "green";
};

interface UseMobileProjectWorkspaceOptions {
  readonly selectedWorkUnitId?: string;
}

export const useMobileProjectWorkspace = ({
  selectedWorkUnitId,
}: UseMobileProjectWorkspaceOptions) => {
  const organization = usePersonalOrganization();
  const projectWorkspace = useProjectWorkspace();
  const chatAgent = useOrganizationChatAgent(organization);
  const signals = useQuery(
    api.signals.list,
    organization.organizationId
      ? { organizationId: organization.organizationId }
      : "skip"
  );
  const assistant: MobileAssistantView = {
    isBusy:
      chatAgent.status === "connecting" ||
      chatAgent.status === "streaming" ||
      chatAgent.status === "submitted",
    messages: toAssistantMessages(chatAgent.messages),
    statusLabel: STATUS_COPY[chatAgent.status],
    statusTone: getStatusTone(chatAgent.status),
  };

  return {
    data: buildMobileWorkspaceView({
      artifacts: projectWorkspace.artifacts,
      assistant,
      events: projectWorkspace.events,
      issues: projectWorkspace.issues,
      organizationLabel: organization.organizationName,
      projects: projectWorkspace.projects,
      selectedProject: projectWorkspace.selectedProject,
      selectedWorkUnitId,
      signals,
    }),
    error: organization.error ?? chatAgent.error,
    organization,
    projectWorkspace,
    raiseIssue: projectWorkspace.raiseIssue,
    raiseIssueFromSignal: (signalId: string) =>
      projectWorkspace.raiseIssueFromSignal(signalId as Id<"signals">),
    sendMessage: chatAgent.sendMessage,
    startWorkUnit: projectWorkspace.startWorkUnit,
  } as const;
};
