'use client';

import { useState } from 'react';
import { useMutation } from 'convex/react';
import { ExternalLink, XCircle } from 'lucide-react';
import { toast } from 'sonner';

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

import { AgentJobDetail } from './agent-job-detail';

const formatTime = (value: number) =>
  new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(value);

export const AgentJobList = ({ jobs }: { jobs: Doc<'agentJobs'>[] }) => {
  const cancel = useMutation(api.agentJobs.cancel);
  const [selectedJobId, setSelectedJobId] = useState<string | null>(
    jobs[0]?._id ?? null,
  );
  const selectedJob = jobs.find((job) => job._id === selectedJobId) ?? jobs[0];

  if (!jobs.length) {
    return (
      <div className='border-border rounded-md border p-5'>
        <h3 className='text-sm font-semibold'>No agent jobs yet</h3>
        <p className='text-muted-foreground mt-1 text-sm'>
          Queue a job to have Spoon open a draft PR against this fork.
        </p>
      </div>
    );
  }

  return (
    <div className='grid gap-4 xl:grid-cols-[0.85fr_1.15fr]'>
      <div className='divide-border overflow-hidden rounded-md border'>
        {jobs.map((job) => (
          <button
            key={job._id}
            type='button'
            className='hover:bg-muted/40 data-[selected=true]:bg-muted/60 block w-full border-b p-3 text-left'
            data-selected={job._id === selectedJob?._id}
            onClick={() => setSelectedJobId(job._id)}
          >
            <div className='flex items-start justify-between gap-3'>
              <div className='min-w-0'>
                <p className='truncate text-sm font-medium'>{job.prompt}</p>
                <p className='text-muted-foreground mt-1 font-mono text-xs'>
                  {job.workBranch}
                </p>
              </div>
              <Badge variant='outline' className='capitalize'>
                {job.status.replaceAll('_', ' ')}
              </Badge>
            </div>
            <div className='text-muted-foreground mt-2 flex flex-wrap gap-2 text-xs'>
              <span>{formatTime(job.createdAt)}</span>
              {job.pullRequestUrl ? (
                <a
                  href={job.pullRequestUrl}
                  target='_blank'
                  rel='noreferrer'
                  className='text-primary inline-flex items-center gap-1'
                >
                  PR <ExternalLink className='size-3' />
                </a>
              ) : null}
            </div>
          </button>
        ))}
      </div>
      {selectedJob ? (
        <div className='space-y-3'>
          {[
            'queued',
            'claimed',
            'preparing',
            'running',
            'checks_running',
          ].includes(selectedJob.status) ? (
            <Button
              type='button'
              variant='outline'
              onClick={async () => {
                try {
                  await cancel({ jobId: selectedJob._id });
                  toast.success('Agent job cancelled.');
                } catch (error) {
                  console.error(error);
                  toast.error('Could not cancel job.');
                }
              }}
            >
              <XCircle className='size-4' />
              Cancel job
            </Button>
          ) : null}
          <AgentJobDetail job={selectedJob} />
        </div>
      ) : null}
    </div>
  );
};
