'use client';

import { MaintenanceQueue } from '@/components/updates/maintenance-queue';
import { useQuery } from 'convex/react';

import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@spoon/ui';

const UpdatesPage = () => {
  const runs = useQuery(api.syncRuns.listRecent, { limit: 50 }) ?? [];
  const spoons = useQuery(api.spoons.listMine, {}) ?? [];
  return (
    <main className='space-y-6'>
      <div>
        <h1 className='text-3xl font-semibold tracking-normal'>Updates</h1>
        <p className='text-muted-foreground mt-2'>
          Upstream checks, merge attempts, and AI reviews will appear here.
        </p>
      </div>
      <div className='flex flex-col gap-3 md:flex-row'>
        <Select defaultValue='all'>
          <SelectTrigger className='w-full md:w-48'>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='all'>All statuses</SelectItem>
            <SelectItem value='needs_review'>Needs review</SelectItem>
            <SelectItem value='conflict'>Conflict</SelectItem>
            <SelectItem value='clean'>Clean</SelectItem>
          </SelectContent>
        </Select>
        <Select defaultValue='all'>
          <SelectTrigger className='w-full md:w-64'>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='all'>All Spoons</SelectItem>
            {spoons.map((spoon) => (
              <SelectItem key={spoon._id} value={spoon._id}>
                {spoon.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Card className='shadow-none'>
        <CardHeader>
          <CardTitle>Recent sync runs</CardTitle>
        </CardHeader>
        <CardContent>
          {runs.length ? (
            <div className='space-y-3'>
              {runs.map((run) => (
                <div key={run._id} className='border-border border p-4'>
                  <p className='font-medium'>{run.kind.replaceAll('_', ' ')}</p>
                  <p className='text-muted-foreground text-sm'>
                    {run.status.replaceAll('_', ' ')}
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <p className='text-muted-foreground'>
              Scheduled upstream checks will appear here once provider
              connections and workers are added.
            </p>
          )}
        </CardContent>
      </Card>
      <section className='space-y-3'>
        <h2 className='text-lg font-semibold'>Maintenance queue</h2>
        <MaintenanceQueue spoons={spoons} />
      </section>
    </main>
  );
};

export default UpdatesPage;
