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

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

import type { PillTab } from '~/components/ui/pill-tabs';
import { ThreadListRow } from '~/components/threads/thread-list-row';
import { AppScreen } from '~/components/ui/app-screen';
import { EmptyState } from '~/components/ui/empty-state';
import { PillTabs } from '~/components/ui/pill-tabs';

type StatusFilter =
  | 'all'
  | 'open'
  | 'running'
  | 'waiting_for_user'
  | 'resolved';

const filters: PillTab<StatusFilter>[] = [
  { label: 'All', value: 'all' },
  { label: 'Open', value: 'open' },
  { label: 'Running', value: 'running' },
  { label: 'Waiting', value: 'waiting_for_user' },
  { label: 'Resolved', value: 'resolved' },
];

const ThreadsRoute = () => {
  const router = useRouter();
  const [status, setStatus] = useState<StatusFilter>('all');
  const [refreshing, setRefreshing] = useState(false);
  const threads =
    useQuery(api.threads.listMine, {
      limit: 50,
      status,
    }) ?? [];

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

  return (
    <AppScreen onRefresh={softRefresh} refreshing={refreshing}>
      <Stack.Screen options={{ title: 'Threads' }} />
      <View>
        <Text className='text-foreground text-3xl font-bold'>Threads</Text>
        <Text className='text-muted-foreground mt-1'>
          Maintenance decisions, user requests, and workspace handoffs.
        </Text>
      </View>
      <PillTabs onChange={setStatus} tabs={filters} value={status} />
      <View className='gap-3'>
        {threads.length ? (
          threads.map((thread) => (
            <ThreadListRow
              key={thread._id}
              thread={thread}
              onPress={() => router.push(`/threads/${thread._id}`)}
            />
          ))
        ) : (
          <EmptyState
            description='Threads appear when you ask Spoon to change a fork or upstream changes need review.'
            title='No threads'
          />
        )}
      </View>
    </AppScreen>
  );
};

export default ThreadsRoute;
