import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../tokens/colors';
import { useNetworkStore } from '../../stores/networkStore';
import { offlineSyncManager } from '../../lib/offlineSync';
import { useQueryClient } from '@tanstack/react-query';
import * as Haptics from 'expo-haptics';

export function NetworkStatusBar() {
  const { isOnline, pendingCount } = useNetworkStore();
  const queryClient = useQueryClient();
  const [isSyncing, setIsSyncing] = React.useState(false);

  const handleSync = async () => {
    if (!isOnline || isSyncing) return;
    
    setIsSyncing(true);
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    
    try {
      await offlineSyncManager.syncAll();
      await queryClient.refetchQueries();
      useNetworkStore.getState().updatePendingCount();
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    } catch (error) {
      console.error('Sync failed:', error);
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
    } finally {
      setIsSyncing(false);
    }
  };

  if (isOnline && pendingCount === 0) {
    return null; // Don't show anything when online and synced
  }

  return (
    <TouchableOpacity
      style={[
        styles.container,
        isOnline ? styles.syncingContainer : styles.offlineContainer,
      ]}
      onPress={handleSync}
      disabled={!isOnline || isSyncing}
      activeOpacity={0.7}
    >
      <Ionicons
        name={isOnline ? (isSyncing ? 'sync' : 'cloud-upload') : 'cloud-offline'}
        size={16}
        color="white"
        style={isSyncing && styles.spinning}
      />
      <Text style={styles.text}>
        {!isOnline
          ? `Offline${pendingCount > 0 ? ` • ${pendingCount} pending` : ''}`
          : isSyncing
          ? 'Syncing...'
          : `${pendingCount} pending • Tap to sync`}
      </Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 8,
    paddingHorizontal: 16,
    gap: 8,
  },
  offlineContainer: {
    backgroundColor: colors.warning,
  },
  syncingContainer: {
    backgroundColor: colors.primary,
  },
  text: {
    color: 'white',
    fontSize: 13,
    fontWeight: '600',
  },
  spinning: {
    // Animation would be added with Reanimated if needed
  },
});
