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

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

import type { PillTab } from '~/components/ui/pill-tabs';
import { AppScreen } from '~/components/ui/app-screen';
import { PillTabs } from '~/components/ui/pill-tabs';
import { WorkspaceArtifacts } from '~/components/workspace/workspace-artifacts';
import { WorkspaceEvents } from '~/components/workspace/workspace-events';
import { WorkspaceMessages } from '~/components/workspace/workspace-messages';
import { WorkspaceSummary } from '~/components/workspace/workspace-summary';

type WorkspaceTab = 'status' | 'messages' | 'diffs' | 'events' | 'artifacts';

const tabs: PillTab<WorkspaceTab>[] = [
  { label: 'Status', value: 'status' },
  { label: 'Messages', value: 'messages' },
  { label: 'Diffs', value: 'diffs' },
  { label: 'Events', value: 'events' },
  { label: 'Artifacts', value: 'artifacts' },
];

const WorkspaceRoute = () => {
  const { jobId: rawJobId } = useLocalSearchParams<{ jobId: string }>();
  const jobId = rawJobId as Id<'agentJobs'>;
  const [tab, setTab] = useState<WorkspaceTab>('status');
  const [refreshing, setRefreshing] = useState(false);
  const [cancelling, setCancelling] = useState(false);
  const job = useQuery(api.agentJobs.get, { jobId });
  const messages = useQuery(api.agentJobs.listMessages, { jobId }) ?? [];
  const events =
    useQuery(api.agentJobs.listEvents, { jobId, limit: 200 }) ?? [];
  const artifacts = useQuery(api.agentJobs.listArtifacts, { jobId }) ?? [];
  const cancel = useMutation(api.agentJobs.cancel);

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

  const cancelJob = async () => {
    setCancelling(true);
    try {
      await cancel({ jobId });
    } catch (error) {
      console.error(error);
      Alert.alert('Could not cancel job.');
    } finally {
      setCancelling(false);
    }
  };

  if (!job) {
    return (
      <AppScreen>
        <Stack.Screen options={{ title: 'Workspace' }} />
        <Text className='text-muted-foreground'>Loading workspace...</Text>
      </AppScreen>
    );
  }

  return (
    <AppScreen onRefresh={softRefresh} refreshing={refreshing}>
      <Stack.Screen options={{ title: 'Workspace' }} />
      <View className='gap-2'>
        <Text className='text-foreground text-3xl font-bold'>
          Workspace review
        </Text>
        <Text className='text-muted-foreground'>
          Inspect the active job without exposing worker internals to mobile.
        </Text>
      </View>
      <PillTabs onChange={setTab} tabs={tabs} value={tab} />
      {tab === 'status' ? (
        <WorkspaceSummary
          cancelling={cancelling}
          job={job}
          onCancel={() => void cancelJob()}
        />
      ) : null}
      {tab === 'messages' ? <WorkspaceMessages messages={messages} /> : null}
      {tab === 'diffs' ? (
        <WorkspaceArtifacts artifacts={artifacts} mode='diffs' />
      ) : null}
      {tab === 'events' ? <WorkspaceEvents events={events} /> : null}
      {tab === 'artifacts' ? (
        <WorkspaceArtifacts artifacts={artifacts} mode='artifacts' />
      ) : null}
    </AppScreen>
  );
};

export default WorkspaceRoute;
