'use client';

import { useQuery } from 'convex/react';

import type { Doc } from '@spoon/backend/convex/_generated/dataModel.js';
import { api } from '@spoon/backend/convex/_generated/api.js';
import { Card, CardContent, CardHeader, CardTitle } from '@spoon/ui';

import { AgentArtifactViewer } from './agent-artifact-viewer';
import { AgentEventLog } from './agent-event-log';

export const AgentJobDetail = ({ job }: { job: Doc<'agentJobs'> }) => {
  const events =
    useQuery(api.agentJobs.listEvents, { jobId: job._id, limit: 200 }) ?? [];
  const artifacts =
    useQuery(api.agentJobs.listArtifacts, { jobId: job._id }) ?? [];

  return (
    <Card className='shadow-none'>
      <CardHeader className='pb-3'>
        <CardTitle className='text-base'>Job details</CardTitle>
      </CardHeader>
      <CardContent className='space-y-5'>
        <div className='grid gap-3 text-sm md:grid-cols-3'>
          <div>
            <p className='text-muted-foreground text-xs'>Status</p>
            <p className='font-medium capitalize'>
              {job.status.replaceAll('_', ' ')}
            </p>
          </div>
          <div>
            <p className='text-muted-foreground text-xs'>Branch</p>
            <p className='font-mono text-xs'>{job.workBranch}</p>
          </div>
          <div>
            <p className='text-muted-foreground text-xs'>Model</p>
            <p className='font-medium'>{job.model}</p>
          </div>
        </div>
        {job.pullRequestUrl ? (
          <a
            href={job.pullRequestUrl}
            target='_blank'
            rel='noreferrer'
            className='text-primary text-sm font-medium underline-offset-4 hover:underline'
          >
            Open draft PR #{job.pullRequestNumber}
          </a>
        ) : null}
        {job.error ? (
          <pre className='border-destructive bg-destructive/5 text-destructive overflow-auto rounded-md border p-3 text-xs whitespace-pre-wrap'>
            {job.error}
          </pre>
        ) : null}
        <section className='space-y-2'>
          <h3 className='text-sm font-semibold'>Events</h3>
          <AgentEventLog events={events} />
        </section>
        <section className='space-y-2'>
          <h3 className='text-sm font-semibold'>Artifacts</h3>
          <AgentArtifactViewer artifacts={artifacts} />
        </section>
      </CardContent>
    </Card>
  );
};
