'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { SpoonStatusBadge } from '@/components/spoons/spoon-status-badge';
import { useQuery } from 'convex/react';
import {
  ArrowUpRight,
  GitBranch,
  MessageSquare,
  RefreshCw,
} from 'lucide-react';

import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  Badge,
  Button,
  Card,
  CardContent,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@spoon/ui';

const formatDate = (value?: number) =>
  value
    ? new Intl.DateTimeFormat('en', { dateStyle: 'medium' }).format(value)
    : 'Never';

const SpoonsPage = () => {
  const router = useRouter();
  const spoons = useQuery(api.spoons.listMineWithState, {}) ?? [];
  const threads = useQuery(api.threads.listMine, { limit: 100 }) ?? [];
  const active = spoons.filter((spoon) => spoon.status === 'active').length;
  const needsReview = threads.filter(
    (thread) =>
      thread.spoonId &&
      !['resolved', 'ignored', 'failed', 'cancelled'].includes(thread.status),
  ).length;
  const upstreamWaiting = spoons.reduce(
    (total, spoon) => total + spoon.effectiveUpstreamAheadBy,
    0,
  );

  return (
    <main className='space-y-6'>
      <div className='flex flex-col justify-between gap-4 md:flex-row md:items-end'>
        <div>
          <h1 className='text-3xl font-semibold tracking-normal'>Spoons</h1>
          <p className='text-muted-foreground mt-2'>
            Managed forks, upstream drift, active maintenance threads, and fork
            metadata in one place.
          </p>
        </div>
        <Button asChild>
          <Link href='/spoons/new'>New Spoon</Link>
        </Button>
      </div>

      <div className='grid gap-3 md:grid-cols-3'>
        <Card className='shadow-none'>
          <CardContent className='flex items-center justify-between p-4'>
            <div>
              <p className='text-muted-foreground text-sm'>Managed</p>
              <p className='text-2xl font-semibold'>{spoons.length}</p>
            </div>
            <GitBranch className='text-muted-foreground size-5' />
          </CardContent>
        </Card>
        <Card className='shadow-none'>
          <CardContent className='flex items-center justify-between p-4'>
            <div>
              <p className='text-muted-foreground text-sm'>Active</p>
              <p className='text-2xl font-semibold'>{active}</p>
            </div>
            <RefreshCw className='text-muted-foreground size-5' />
          </CardContent>
        </Card>
        <Card className='shadow-none'>
          <CardContent className='flex items-center justify-between p-4'>
            <div>
              <p className='text-muted-foreground text-sm'>Open threads</p>
              <p className='text-2xl font-semibold'>{needsReview}</p>
            </div>
            <MessageSquare className='text-muted-foreground size-5' />
          </CardContent>
        </Card>
      </div>

      {spoons.length ? (
        <Card className='shadow-none'>
          <CardContent className='p-0'>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className='pl-4'>Spoon</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Fork</TableHead>
                  <TableHead>Drift</TableHead>
                  <TableHead>Cadence</TableHead>
                  <TableHead>Last checked</TableHead>
                  <TableHead className='pr-4 text-right'>Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {spoons.map((spoon) => {
                  const href = `/spoons/${spoon._id}`;
                  return (
                    <TableRow
                      key={spoon._id}
                      role='link'
                      tabIndex={0}
                      className='hover:bg-muted/50 cursor-pointer'
                      onClick={() => router.push(href)}
                      onKeyDown={(event) => {
                        if (event.key === 'Enter' || event.key === ' ') {
                          event.preventDefault();
                          router.push(href);
                        }
                      }}
                    >
                      <TableCell className='pl-4'>
                        <Link
                          href={href}
                          className='group inline-flex min-w-0 flex-col'
                          onClick={(event) => event.stopPropagation()}
                        >
                          <span className='group-hover:text-primary font-medium transition-colors'>
                            {spoon.name}
                          </span>
                          <span className='text-muted-foreground text-xs'>
                            {spoon.upstreamOwner}/{spoon.upstreamRepo}
                          </span>
                        </Link>
                      </TableCell>
                      <TableCell>
                        <SpoonStatusBadge
                          status={spoon.syncStatus ?? spoon.status}
                        />
                      </TableCell>
                      <TableCell>
                        {spoon.forkOwner && spoon.forkRepo ? (
                          <span className='font-medium'>
                            {spoon.forkOwner}/{spoon.forkRepo}
                          </span>
                        ) : (
                          <Badge variant='outline'>Missing metadata</Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className='text-sm'>
                          <p>{spoon.effectiveUpstreamAheadBy} actionable</p>
                          <p className='text-muted-foreground'>
                            {spoon.rawUpstreamAheadBy} raw upstream ·{' '}
                            {spoon.forkAheadBy} fork-only
                          </p>
                          {spoon.ignoredUpstreamCount ? (
                            <p className='text-muted-foreground'>
                              {spoon.ignoredUpstreamCount} ignored
                            </p>
                          ) : null}
                        </div>
                      </TableCell>
                      <TableCell className='capitalize'>
                        {spoon.syncCadence}
                      </TableCell>
                      <TableCell>{formatDate(spoon.lastCheckedAt)}</TableCell>
                      <TableCell className='pr-4 text-right'>
                        <Button size='sm' variant='outline' asChild>
                          <Link
                            href={href}
                            onClick={(event) => event.stopPropagation()}
                          >
                            Open
                            <ArrowUpRight className='size-3' />
                          </Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        <Card className='shadow-none'>
          <CardContent className='p-8'>
            <p className='text-lg font-medium'>No managed forks yet</p>
            <p className='text-muted-foreground mt-2 max-w-xl'>
              Add your first Spoon manually. Provider-backed forking can build
              on this same record later.
            </p>
            <Button className='mt-5' asChild>
              <Link href='/spoons/new'>Create Spoon</Link>
            </Button>
          </CardContent>
        </Card>
      )}

      {spoons.length ? (
        <p className='text-muted-foreground text-sm'>
          Actionable upstream commits waiting across all Spoons:{' '}
          {upstreamWaiting}
        </p>
      ) : null}
    </main>
  );
};

export default SpoonsPage;
