import React from 'react';
import { 
  RefreshControl, 
  Platform, 
  StyleSheet, 
  View,
  StatusBar
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { useAppTheme } from '../context/ThemeContext';
import { useRefresh } from '../context/RefreshContext';

interface AppScreenProps {
  children: React.ReactNode;
  scrollable?: boolean;
  onRefresh?: () => Promise<void>;
  containerStyle?: any;
}


export const AppScreen = ({ children, scrollable = true, onRefresh, containerStyle }: AppScreenProps) => {
  const { colors, isDark } = useAppTheme();
  const { refreshing, refreshAll } = useRefresh();
  const insets = useSafeAreaInsets();

  const handleRefresh = async () => {
    await refreshAll();
    if (onRefresh) {
      await onRefresh();
    }
  };

  const bg = isDark ? '#111111' : '#F5F5F5';

  const content = (
    <KeyboardAwareScrollView
      style={{ flex: 1 }}
      contentContainerStyle={{ flexGrow: 1 }}
      showsVerticalScrollIndicator={false}
      enableOnAndroid={true}
      extraScrollHeight={Platform.OS === 'ios' ? 40 : 60}
      keyboardShouldPersistTaps="handled"
      refreshControl={
        <RefreshControl 
          refreshing={refreshing} 
          onRefresh={handleRefresh} 
          tintColor={colors.primary}
          colors={[colors.primary]}
          progressBackgroundColor={isDark ? '#1A1A1A' : '#FFFFFF'}
        />
      }
    >
      <View style={{ flex: 1, paddingBottom: insets.bottom }}>
        {children}
      </View>
    </KeyboardAwareScrollView>
  );

  return (
    <View style={[styles.container, { backgroundColor: bg }, containerStyle]}>
      <StatusBar barStyle={isDark ? "light-content" : "dark-content"} translucent backgroundColor="transparent" />
      
      {/* Handling top padding manually for more control than default SafeAreaView */}
      <View style={[
        { flex: 1, paddingTop: insets.top },
        Platform.OS === 'web' && styles.webMaxWidth
      ]}>
        {scrollable ? content : <View style={{ flex: 1, paddingBottom: insets.bottom }}>{children}</View>}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webMaxWidth: {
    width: '100%',
    backgroundColor: 'transparent',
  }
});
