import React from 'react';
import { ActivityIndicator, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { OutboxCounts } from '../db/outbox';
import { useIsOnline } from '../net/connectivity';

export function SyncStatusBar({
  counts,
  syncing,
  onPress,
}: {
  counts: OutboxCounts;
  syncing: boolean;
  onPress?: () => void;
}) {
  const online = useIsOnline();
  const pendientes = counts.pending + counts.mediaPending;
  const hasProblems = counts.conflict > 0 || counts.error > 0;

  const content = (
    <View style={[styles.bar, { backgroundColor: online ? '#1f6f43' : '#8a6d00' }]}>
      {syncing && <ActivityIndicator color="#fff" size="small" />}
      <Text style={styles.text}>
        {online ? 'En línea' : 'Sin conexión'}
        {pendientes > 0 ? ` · ${pendientes} en cola` : ' · al día'}
        {counts.conflict > 0 ? ` · ${counts.conflict} conflicto(s)` : ''}
        {counts.error > 0 ? ` · ${counts.error} error(es)` : ''}
      </Text>
      {hasProblems && onPress ? <Text style={styles.chevron}>revisar ›</Text> : null}
    </View>
  );

  if (onPress) {
    return (
      <TouchableOpacity activeOpacity={0.8} onPress={onPress}>
        {content}
      </TouchableOpacity>
    );
  }
  return content;
}

const styles = StyleSheet.create({
  bar: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  text: { color: '#fff', fontSize: 13, fontWeight: '600', flex: 1 },
  chevron: { color: '#fff', fontSize: 12, fontWeight: '700', textDecorationLine: 'underline' },
});
