import React, { useCallback } from 'react';
import {
  View,
  ScrollView,
  Text,
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  RefreshControl,
  StatusBar,
} from 'react-native';
import { useCommunity } from '../../hooks/useCommunity';
import { LoadingState } from '../../components/ui/LoadingState';
import { ErrorState } from '../../components/ui/ErrorState';
import { EmptyState } from '../../components/ui/EmptyState';
import { Theme } from '../../constants/Theme';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Theme.colors.background,
  },
  header: {
    backgroundColor: Theme.colors.surface,
    padding: Theme.spacing.l,
    borderBottomWidth: 1,
    borderBottomColor: Theme.colors.border,
  },
  headerTitle: {
    ...Theme.typography.heading,
    color: Theme.colors.primary,
  },
  section: {
    paddingHorizontal: Theme.spacing.m,
    marginTop: Theme.spacing.l,
  },
  communityCard: {
    backgroundColor: Theme.colors.surface,
    borderRadius: Theme.borderRadius.l,
    padding: Theme.spacing.m,
    marginBottom: Theme.spacing.s,
    ...Theme.shadows.small,
  },
  communityCardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: Theme.spacing.s,
  },
  communityIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: Theme.colors.secondaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: Theme.spacing.m,
  },
  communityTitle: {
    ...Theme.typography.subheading,
    color: Theme.colors.text,
  },
  communityDescription: {
    ...Theme.typography.body,
    fontSize: 14,
    color: Theme.colors.textMuted,
    marginBottom: Theme.spacing.m,
  },
  memberCount: {
    ...Theme.typography.caption,
    color: Theme.colors.primary,
    fontWeight: '600',
    marginBottom: Theme.spacing.s,
  },
  joinButton: {
    backgroundColor: Theme.colors.primary,
    paddingVertical: 10,
    paddingHorizontal: Theme.spacing.m,
    borderRadius: Theme.borderRadius.round,
    alignItems: 'center',
  },
  joinButtonText: {
    color: Theme.colors.textLight,
    fontSize: 14,
    fontWeight: '600',
  },
  sectionTitle: {
    ...Theme.typography.subheading,
    color: Theme.colors.text,
    marginBottom: Theme.spacing.s,
  },
  postCard: {
    backgroundColor: Theme.colors.surface,
    borderRadius: Theme.borderRadius.m,
    padding: Theme.spacing.m,
    marginBottom: Theme.spacing.s,
    ...Theme.shadows.small,
  },
  postHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: Theme.spacing.s,
  },
  postAuthor: {
    fontWeight: '600',
    fontSize: 14,
    color: Theme.colors.text,
  },
  postTime: {
    color: Theme.colors.textMuted,
    fontSize: 12,
  },
  postContent: {
    ...Theme.typography.body,
    fontSize: 14,
    color: Theme.colors.text,
    marginBottom: Theme.spacing.m,
  },
  postFooter: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderTopColor: Theme.colors.border,
    paddingTop: Theme.spacing.s,
  },
  postStat: {
    marginRight: Theme.spacing.m,
    color: Theme.colors.textMuted,
    fontSize: 12,
    fontWeight: '500',
  },
});

export default function CommunityScreen() {
  const { data: posts, isLoading, isError, refetch } = useCommunity();

  const onRefresh = useCallback(() => {
    refetch();
  }, [refetch]);

  const communities = [
    {
      title: 'Support Group',
      description: 'Join our growing community of folks navigating chronic illness and cancer. Connect, share, and find strength together.',
      members: '2,341 members',
      icon: '👥',
    },
    {
      title: 'The Living Room',
      description: 'Exclusive support circle for members. A safe space to share your journey, connect with others, and find support.',
      members: '856 members',
      icon: '🛋️',
    },
    {
      title: 'The Journal',
      description: 'Read inspiring stories from our community members as they navigate their journeys. Share your own story.',
      members: '1,203 stories',
      icon: '📖',
    },
    {
      title: 'Podcast Community',
      description: 'Discuss episodes of our podcast and connect with listeners who share your experiences.',
      members: '432 members',
      icon: '🎙️',
    },
  ];

  if (isLoading) {
    return <LoadingState message="Loading community..." />;
  }

  if (isError) {
    return <ErrorState message="Failed to load community content" onRetry={refetch} />;
  }

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor={Theme.colors.background} />
      <ScrollView
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isLoading}
            onRefresh={onRefresh}
            tintColor={Theme.colors.primary}
            colors={[Theme.colors.primary]}
          />
        }
      >
        <View style={styles.header}>
          <Text style={styles.headerTitle}>Community</Text>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Join Our Communities</Text>
        </View>

        {communities.map((community, index) => (
          <View key={index} style={styles.section}>
            <View style={styles.communityCard}>
              <View style={styles.communityCardHeader}>
                <View style={styles.communityIcon}>
                  <Text style={{ fontSize: 24 }}>{community.icon}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={styles.communityTitle}>{community.title}</Text>
                  <Text style={styles.memberCount}>{community.members}</Text>
                </View>
              </View>
              <Text style={styles.communityDescription}>{community.description}</Text>
              <TouchableOpacity style={styles.joinButton}>
                <Text style={styles.joinButtonText}>Join Community</Text>
              </TouchableOpacity>
            </View>
          </View>
        ))}

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Recent Activity</Text>
        </View>

        {!posts || posts.length === 0 ? (
          <View style={styles.section}>
            <EmptyState title="No Recent Activity" message="Be the first to post!" />
          </View>
        ) : (
          posts.map((post) => (
            <View key={post.id} style={styles.section}>
              <View style={styles.postCard}>
                <View style={styles.postHeader}>
                  <Text style={styles.postAuthor}>{post.author}</Text>
                  <Text style={styles.postTime}>{post.timestamp}</Text>
                </View>
                <Text style={styles.postContent}>{post.content}</Text>
                <View style={styles.postFooter}>
                  <Text style={styles.postStat}>{post.likes} Likes</Text>
                  <Text style={styles.postStat}>{post.comments} Comments</Text>
                </View>
              </View>
            </View>
          ))
        )}

        <View style={[styles.section, { marginBottom: 40 }]}>
          <View style={[styles.communityCard, { backgroundColor: Theme.colors.secondaryLight }]}>
            <Text style={[styles.communityTitle, { color: Theme.colors.primaryDark }]}>Community Guidelines</Text>
            <Text style={[styles.communityDescription, { marginTop: 8, color: Theme.colors.primaryDark }]}>
              • Be respectful and supportive{'\n'}
              • Share your authentic story{'\n'}
              • Respect others' privacy{'\n'}
              • No medical advice{'\n'}
              • Check in, not out
            </Text>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
