import { useState } from 'react';
import { Text, View } from 'react-native';
import { Link, Stack, useRouter } from 'expo-router';
import { useQuery } from 'convex/react';

import { api } from '@spoon/backend/convex/_generated/api.js';

import { SpoonListRow } from '~/components/spoons/spoon-list-row';
import { AppScreen } from '~/components/ui/app-screen';
import { Button } from '~/components/ui/button';
import { EmptyState } from '~/components/ui/empty-state';
import { MetricCard } from '~/components/ui/metric-card';

const openThreadStatuses = ['resolved', 'ignored', 'failed', 'cancelled'];

const SpoonsRoute = () => {
  const router = useRouter();
  const [refreshing, setRefreshing] = useState(false);
  const spoons = useQuery(api.spoons.listMine, {}) ?? [];
  const threads = useQuery(api.threads.listMine, { limit: 100 }) ?? [];
  const active = spoons.filter((spoon) => spoon.status === 'active').length;
  const upstreamWaiting = spoons.reduce(
    (total, spoon) => total + (spoon.upstreamAheadBy ?? 0),
    0,
  );

  const openThreadsFor = (spoonId: string) =>
    threads.filter(
      (thread) =>
        thread.spoonId === spoonId &&
        !openThreadStatuses.includes(thread.status),
    ).length;

  const softRefresh = () => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 600);
  };

  return (
    <AppScreen onRefresh={softRefresh} refreshing={refreshing}>
      <Stack.Screen options={{ title: 'Spoons' }} />
      <View className='flex-row items-start justify-between gap-3'>
        <View className='min-w-0 flex-1'>
          <Text className='text-foreground text-3xl font-bold'>Spoons</Text>
          <Text className='text-muted-foreground mt-1'>
            Managed forks and their relationship with upstream.
          </Text>
        </View>
        <Link href='/spoons/new' asChild>
          <Button>New</Button>
        </Link>
      </View>

      <View className='flex-row gap-3'>
        <MetricCard label='Managed' value={spoons.length} />
        <MetricCard label='Active' value={active} />
        <MetricCard label='Waiting' value={upstreamWaiting} />
      </View>

      <View className='gap-3'>
        {spoons.length ? (
          spoons.map((spoon) => (
            <SpoonListRow
              key={spoon._id}
              openThreads={openThreadsFor(spoon._id)}
              spoon={spoon}
              onPress={() => router.push(`/spoons/${spoon._id}`)}
            />
          ))
        ) : (
          <EmptyState
            description='Create a manual Spoon record to start shaping fork maintenance.'
            title='No managed forks yet'
          />
        )}
      </View>
    </AppScreen>
  );
};

export default SpoonsRoute;
