import { useCallback, useState } from 'react';
import {
  ActivityIndicator,
  FlatList,
  Pressable,
  RefreshControl,
  Text,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import type { Network } from '@/api/types';
import { useNetworks } from '@/hooks/use-networks';
import { useAuthStore } from '@/stores/auth-store';
import { toUserMessage } from '@/lib/errors';
import type { RootStackScreenProps } from '@/navigation/types';
import { FlowyLogo } from '@/components/FlowyLogo';
import { ListSeparator } from '@/components/ListSeparator';
import { Drawer } from './Drawer';

export function NetworkListScreen({
  navigation,
}: RootStackScreenProps<'NetworkList'>) {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const { data, isLoading, refetch, error } = useNetworks();
  const user = useAuthStore((s) => s.user);
  const initials = user?.email_prefix.slice(0, 2).toUpperCase() ?? '??';

  // Local refreshing state — driving RefreshControl from react-query's
  // isRefetching can leave the native spinner visually stuck after the
  // screen is detached/reattached by native-stack.
  const [refreshing, setRefreshing] = useState(false);
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      await refetch();
    } finally {
      setRefreshing(false);
    }
  }, [refetch]);

  return (
    <SafeAreaView className="flex-1 bg-background" edges={['top']}>
      <View className="flex-row items-center justify-between px-4 py-3 border-b border-border">
        <Pressable
          onPress={() => setDrawerOpen(true)}
          accessibilityLabel="Open menu"
          className="bg-muted h-9 w-9 items-center justify-center rounded-full"
        >
          <Text className="text-muted-foreground text-xs font-semibold">
            {initials}
          </Text>
        </Pressable>
        <FlowyLogo />
        <View className="w-9" />
      </View>

      {isLoading ? (
        <View className="flex-1 items-center justify-center">
          <ActivityIndicator />
        </View>
      ) : error ? (
        <View className="flex-1 items-center justify-center px-6">
          <Text className="text-destructive text-center">
            {toUserMessage(error)}
          </Text>
          <Pressable onPress={() => refetch()} className="mt-3 px-4 py-2">
            <Text className="text-foreground font-medium">Retry</Text>
          </Pressable>
        </View>
      ) : !data || data.length === 0 ? (
        <EmptyState />
      ) : (
        <FlatList
          data={data}
          keyExtractor={(item) => item.id}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          ItemSeparatorComponent={ListSeparator}
          renderItem={({ item }) => (
            <NetworkCard
              network={item}
              onPress={() =>
                navigation.navigate('StreamList', { networkId: item.id })
              }
            />
          )}
        />
      )}

      <Drawer
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        onNavigateAccount={() => navigation.navigate('Account')}
        onNavigateSettings={() => navigation.navigate('Settings')}
      />
    </SafeAreaView>
  );
}

function NetworkCard({
  network,
  onPress,
}: {
  network: Network;
  onPress: () => void;
}) {
  return (
    <Pressable
      onPress={onPress}
      className="active:bg-accent flex-row items-center justify-between px-4 py-4"
    >
      <View className="flex-1">
        <Text className="text-foreground text-base font-semibold">
          {network.name}
        </Text>
        <Text className="text-muted-foreground text-sm">
          {network.humans.length}{' '}
          {network.humans.length === 1 ? 'member' : 'members'}
        </Text>
      </View>
      <Text className="text-muted-foreground text-xl">›</Text>
    </Pressable>
  );
}

function EmptyState() {
  return (
    <View className="flex-1 items-center justify-center px-6">
      <Text className="text-foreground text-lg font-medium text-center">
        You aren’t in any networks yet.
      </Text>
      <Text className="text-muted-foreground mt-2 text-center">
        Ask a friend for an invite, or create one on desktop.
      </Text>
    </View>
  );
}
