/**
 * Beneficiaries Screen
 * View and manage beneficiaries
 */

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 { ApiService } from '../../services/ApiService';
import { AuthService } from '../../services/AuthService';
import Toast from 'react-native-toast-message';

export default function BeneficiariesScreen() {
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [beneficiaries, setBeneficiaries] = useState([]);

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

  const loadBeneficiaries = async () => {
    try {
      setLoading(true);
      const user = await AuthService.getCurrentUser();
      if (user && user.member_id) {
        const response = await ApiService.get('/beneficiaries', {
          member_id: user.member_id,
        });
        if (response.success) {
          setBeneficiaries(response.data || []);
        }
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to load beneficiaries',
      });
    } finally {
      setLoading(false);
    }
  };

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

  const renderBeneficiary = ({ item }) => (
    <View style={styles.beneficiaryCard}>
      <View style={styles.beneficiaryHeader}>
        <View style={styles.beneficiaryIcon}>
          <Icon name="account" size={24} color="#3b82f6" />
        </View>
        <View style={styles.beneficiaryInfo}>
          <Text style={styles.beneficiaryName}>
            {item.first_name} {item.last_name}
          </Text>
          <Text style={styles.beneficiaryRelation}>{item.relationship}</Text>
        </View>
        <Text style={styles.percentage}>{item.percentage}%</Text>
      </View>
    </View>
  );

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

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContent: {
    padding: 16,
  },
  beneficiaryCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  beneficiaryHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  beneficiaryIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#dbeafe',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  beneficiaryInfo: {
    flex: 1,
  },
  beneficiaryName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
  },
  beneficiaryRelation: {
    fontSize: 14,
    color: '#6b7280',
    marginTop: 4,
  },
  percentage: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#3b82f6',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 64,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 16,
  },
});
