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 { ThreadListRow } from '~/components/threads/thread-list-row';
import { AppScreen } from '~/components/ui/app-screen';
import { Button } from '~/components/ui/button';
import { Card } from '~/components/ui/card';
import { EmptyState } from '~/components/ui/empty-state';
import { MetricCard } from '~/components/ui/metric-card';
import { titleize } from '~/utils/format';

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

const DashboardRoute = () => {
  const router = useRouter();
  const [refreshing, setRefreshing] = useState(false);
  const spoons = useQuery(api.spoons.listMine, {}) ?? [];
  const syncRuns = useQuery(api.syncRuns.listRecent, { limit: 5 }) ?? [];
  const threads = useQuery(api.threads.listMine, { limit: 25 }) ?? [];
  const active = spoons.filter((spoon) => spoon.status === 'active').length;
  const behind = spoons.filter((spoon) => spoon.syncStatus === 'behind').length;
  const diverged = spoons.filter(
    (spoon) => spoon.syncStatus === 'diverged',
  ).length;
  const openThreads = threads.filter(
    (thread) => !openThreadStatuses.includes(thread.status),
  );
  const upstreamWaiting = spoons.reduce(
    (total, spoon) => total + (spoon.upstreamAheadBy ?? 0),
    0,
  );

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

  return (
    <AppScreen onRefresh={softRefresh} refreshing={refreshing}>
      <Stack.Screen options={{ title: 'Dashboard' }} />
      <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'>Dashboard</Text>
          <Text className='text-muted-foreground mt-1'>
            Managed forks, upstream drift, and open maintenance threads.
          </Text>
        </View>
        <Link href='/spoons/new' asChild>
          <Button>New</Button>
        </Link>
      </View>

      <View className='gap-3'>
        <View className='flex-row gap-3'>
          <MetricCard
            label='Spoons'
            note={`${active} active`}
            value={spoons.length}
          />
          <MetricCard
            label='Behind'
            note={`${diverged} diverged`}
            value={behind}
          />
        </View>
        <View className='flex-row gap-3'>
          <MetricCard label='Open threads' value={openThreads.length} />
          <MetricCard label='Upstream commits' value={upstreamWaiting} />
        </View>
      </View>

      <View className='gap-3'>
        <Text className='text-foreground text-lg font-semibold'>
          Maintenance queue
        </Text>
        {openThreads.length ? (
          openThreads
            .slice(0, 5)
            .map((thread) => (
              <ThreadListRow
                key={thread._id}
                thread={thread}
                onPress={() => router.push(`/threads/${thread._id}`)}
              />
            ))
        ) : (
          <EmptyState
            description='Threads appear when you request work or upstream changes need review.'
            title='No open maintenance threads'
          />
        )}
      </View>

      <View className='gap-3'>
        <Text className='text-foreground text-lg font-semibold'>
          Recent Spoons
        </Text>
        {spoons.length ? (
          spoons
            .slice(0, 5)
            .map((spoon) => (
              <SpoonListRow
                key={spoon._id}
                spoon={spoon}
                onPress={() => router.push(`/spoons/${spoon._id}`)}
              />
            ))
        ) : (
          <EmptyState
            description='Create your first managed fork to start tracking upstream drift.'
            title='No Spoons yet'
          />
        )}
      </View>

      <View className='gap-3'>
        <Text className='text-foreground text-lg font-semibold'>
          Recent activity
        </Text>
        <Card className='gap-3'>
          {syncRuns.length ? (
            syncRuns.map((run) => (
              <View key={run._id} className='border-border border-b pb-3'>
                <Text className='text-foreground font-medium'>
                  {titleize(run.kind)}
                </Text>
                <Text className='text-muted-foreground text-sm'>
                  {titleize(run.status)}
                </Text>
              </View>
            ))
          ) : (
            <Text className='text-muted-foreground text-sm'>
              Upstream checks will appear here.
            </Text>
          )}
        </Card>
      </View>
    </AppScreen>
  );
};

export default DashboardRoute;
