'use client';

import { useEffect } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { AgentWorkspaceShell } from '@/components/agent-workspace/agent-workspace-shell';
import { useQuery } from 'convex/react';
import { ArrowLeft } from 'lucide-react';

import type { Id } from '@spoon/backend/convex/_generated/dataModel.js';
import { api } from '@spoon/backend/convex/_generated/api.js';
import { Button } from '@spoon/ui';

const AgentWorkspacePage = () => {
  const router = useRouter();
  const params = useParams<{ spoonId: string; jobId: string }>();
  const jobId = params.jobId as Id<'agentJobs'>;
  const job = useQuery(api.agentJobs.get, { jobId });

  useEffect(() => {
    if (job?.threadId) router.replace(`/threads/${job.threadId}`);
  }, [job?.threadId, router]);

  if (job?.threadId) {
    return (
      <main className='text-muted-foreground p-6'>
        Opening thread workspace...
      </main>
    );
  }

  return (
    <main className='space-y-4'>
      <Button asChild variant='ghost' size='sm'>
        <Link href={`/spoons/${params.spoonId}`}>
          <ArrowLeft className='size-4' />
          Back to Spoon
        </Link>
      </Button>
      <AgentWorkspaceShell jobId={jobId} />
    </main>
  );
};

export default AgentWorkspacePage;
