/**
 * Contributions Screen
 * View contribution history
 */

import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useNavigation } from '@react-navigation/native';
import { AuthService } from '../../services/AuthService';
import { MemberService } from '../../services/MemberService';
import Toast from 'react-native-toast-message';
import { format } from 'date-fns';

export default function ContributionsScreen() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [contributions, setContributions] = useState([]);
  const [memberId, setMemberId] = useState(null);

  useEffect(() => {
    loadContributions();
  }, []);

  const loadContributions = async () => {
    try {
      setLoading(true);
      const user = await AuthService.getCurrentUser();
      if (user && user.member_id) {
        setMemberId(user.member_id);
        const response = await MemberService.getContributions(user.member_id);
        if (response.success) {
          setContributions(response.data || []);
        }
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to load contributions',
      });
    } finally {
      setLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await loadContributions();
    setRefreshing(false);
  };

  const renderContribution = ({ item }) => (
    <TouchableOpacity
      style={styles.contributionCard}
      onPress={() => navigation.navigate('ContributionDetails', { contribution: item })}
    >
      <View style={styles.contributionHeader}>
        <View style={styles.contributionIcon}>
          <Icon name="wallet" size={24} color="#10b981" />
        </View>
        <View style={styles.contributionInfo}>
          <Text style={styles.contributionType}>{item.contribution_type}</Text>
          <Text style={styles.contributionPeriod}>
            {format(new Date(item.contribution_period), 'MMM yyyy')}
          </Text>
        </View>
        <View style={styles.contributionAmount}>
          <Text style={styles.amount}>KES {parseFloat(item.contribution_amount).toLocaleString()}</Text>
          <View style={[
            styles.statusBadge,
            item.status === 'PROCESSED' ? styles.statusProcessed : styles.statusPending
          ]}>
            <Text style={styles.statusText}>{item.status}</Text>
          </View>
        </View>
      </View>
      <View style={styles.contributionFooter}>
        <Text style={styles.contributionDate}>
          Posted: {format(new Date(item.created_at), 'dd MMM yyyy')}
        </Text>
        {item.reference_number && (
          <Text style={styles.reference}>Ref: {item.reference_number}</Text>
        )}
      </View>
    </TouchableOpacity>
  );

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#2563eb" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={contributions}
        renderItem={renderContribution}
        keyExtractor={(item) => item.contribution_id.toString()}
        contentContainerStyle={styles.listContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Icon name="wallet-outline" size={64} color="#9ca3af" />
            <Text style={styles.emptyText}>No contributions found</Text>
          </View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContent: {
    padding: 16,
  },
  contributionCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  contributionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  contributionIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#d1fae5',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  contributionInfo: {
    flex: 1,
  },
  contributionType: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
  },
  contributionPeriod: {
    fontSize: 14,
    color: '#6b7280',
    marginTop: 4,
  },
  contributionAmount: {
    alignItems: 'flex-end',
  },
  amount: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#10b981',
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
    marginTop: 4,
  },
  statusProcessed: {
    backgroundColor: '#d1fae5',
  },
  statusPending: {
    backgroundColor: '#fef3c7',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
    color: '#065f46',
  },
  contributionFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
  },
  contributionDate: {
    fontSize: 12,
    color: '#6b7280',
  },
  reference: {
    fontSize: 12,
    color: '#6b7280',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 64,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 16,
  },
});
