'use client';

import React, { useEffect } from "react";
import ASide from "./components/ASide";
import Flow from "./components/Flow";
import Header from "./components/Header";
import NodeRender from "./components/NodeRender";
import { trpc } from "@/lib/trpc";
import { useQuery } from '@tanstack/react-query'
import { useSearchParam } from 'react-use';
import { useSession, signIn, signOut } from "next-auth/react"
import { useAtom, useSetAtom, useAtomValue } from "jotai";
import { flowModelAtom, flowModelRecordAtom } from "./store";


const RunAgentFlow = () => {
  const multiAgentId = useSearchParam('multiAgentId')
  if (!multiAgentId) {
    // FIXME redirect to 404
  }
  const flowModelRecordQuery = trpc.flowModel.byId.useQuery({ multiAgentId })
  if (flowModelRecordQuery.isError) {
    // FIXME redirect to 500
  }
  const setFlowModelRecord = useSetAtom(flowModelRecordAtom)
  useEffect(() => {
    setFlowModelRecord(flowModelRecordQuery.data)
  }, [flowModelRecordQuery.data])

  return (
    <main className="flex h-screen overflow-hidden flex-col items-stretch justify-between p-2 gap-2">
      <Header></Header>
      <div className="flex align-stretch flex-1 gap-2 overflow-hidden">
        <div className="flex-1 flex flex-col align-stretch min-w-0 gap-2">
          <Flow></Flow>
          <NodeRender></NodeRender>
        </div>
        <ASide></ASide>
      </div>
    </main>
  )
}

export default React.memo(RunAgentFlow)