import React, { useRef, useEffect } from 'react';
import { View, ScrollView, FlatList, StyleSheet, RefreshControl, Animated, StatusBar } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Header } from '../common/Header';
import { SkeletonDashboard } from '../ui/Skeleton';
import { colors } from '../../theme';
import { Ionicons } from '@expo/vector-icons';
import { useResponsive } from '../../hooks/useResponsive';

interface ScreenContainerProps {
  title: string;
  subtitle?: string;
  onBack?: () => void;
  rightAction?: { icon: keyof typeof Ionicons.glyphMap; onPress: () => void };
  rightActions?: Array<{ icon: keyof typeof Ionicons.glyphMap; onPress: () => void }>;
  loading?: boolean;
  refreshing?: boolean;
  onRefresh?: () => void;
  children: React.ReactNode;
  scroll?: boolean;
  contentPadding?: number;
  headerContent?: React.ReactNode;
  noBottomPad?: boolean;
}

export function ScreenContainer({
  title,
  subtitle,
  onBack,
  rightAction,
  rightActions,
  loading = false,
  refreshing = false,
  onRefresh,
  children,
  scroll = true,
  contentPadding: contentPaddingProp,
  headerContent,
  noBottomPad = false,
}: ScreenContainerProps) {
  const insets = useSafeAreaInsets();
  const { contentPadding: responsivePadding } = useResponsive();
  const contentPadding = contentPaddingProp ?? responsivePadding;
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, { toValue: 1, duration: 300, useNativeDriver: true }).start();
  }, []);

  if (loading) {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" backgroundColor={colors.white} />
        <Header title={title} subtitle={subtitle} onBack={onBack} rightAction={rightAction} rightActions={rightActions} />
        <SkeletonDashboard />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor={colors.white} />
      <Header title={title} subtitle={subtitle} onBack={onBack} rightAction={rightAction} rightActions={rightActions} />
      {headerContent}
      <Animated.View style={[styles.content, { opacity: fadeAnim, flex: 1 }]}>
        {scroll ? (
          <ScrollView
            contentContainerStyle={[
              styles.scrollContent,
              { padding: contentPadding, paddingBottom: noBottomPad ? contentPadding : 100 },
            ]}
            showsVerticalScrollIndicator={false}
            keyboardShouldPersistTaps="handled"
            refreshControl={
              onRefresh ? (
                <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.primary[500]} />
              ) : undefined
            }
          >
            {children}
          </ScrollView>
        ) : (
          children
        )}
      </Animated.View>
    </View>
  );
}

interface ScreenListContainerProps<T> {
  title: string;
  subtitle?: string;
  onBack?: () => void;
  rightAction?: { icon: keyof typeof Ionicons.glyphMap; onPress: () => void };
  rightActions?: Array<{ icon: keyof typeof Ionicons.glyphMap; onPress: () => void }>;
  loading?: boolean;
  refreshing?: boolean;
  onRefresh?: () => void;
  data: T[];
  keyExtractor: (item: T) => string;
  renderItem: (info: { item: T; index: number }) => React.ReactElement;
  ListEmptyComponent?: React.ReactElement;
  ListFooterComponent?: React.ReactElement;
  contentPadding?: number;
  headerContent?: React.ReactNode;
  toolbar?: React.ReactNode;
}

export function ScreenListContainer<T>({
  title,
  subtitle,
  onBack,
  rightAction,
  rightActions,
  loading = false,
  refreshing = false,
  onRefresh,
  data,
  keyExtractor,
  renderItem,
  ListEmptyComponent,
  ListFooterComponent,
  contentPadding: contentPaddingProp,
  headerContent,
  toolbar,
}: ScreenListContainerProps<T>) {
  const { contentPadding: responsivePadding } = useResponsive();
  const contentPadding = contentPaddingProp ?? responsivePadding;
  if (loading) {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" backgroundColor={colors.white} />
        <Header title={title} subtitle={subtitle} onBack={onBack} rightAction={rightAction} rightActions={rightActions} />
        <SkeletonDashboard />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor={colors.white} />
      <Header title={title} subtitle={subtitle} onBack={onBack} rightAction={rightAction} rightActions={rightActions} />
      {headerContent}
      {toolbar}
      <FlatList
        data={data}
        keyExtractor={keyExtractor}
        renderItem={renderItem}
        contentContainerStyle={[styles.listContent, { paddingHorizontal: contentPadding, paddingBottom: 100 }]}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        refreshControl={
          onRefresh ? (
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.primary[500]} />
          ) : undefined
        }
        ListEmptyComponent={ListEmptyComponent}
        ListFooterComponent={ListFooterComponent}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {},
  scrollContent: {
    paddingTop: 16,
  },
  listContent: {
    paddingTop: 16,
  },
});
