/**
 * Premiums Screen
 * View premium payment history
 */

import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  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';
import { format } from 'date-fns';

export default function PremiumsScreen() {
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [premiums, setPremiums] = useState([]);

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

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

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

  const renderPremium = ({ item }) => (
    <View style={styles.premiumCard}>
      <View style={styles.premiumHeader}>
        <View style={styles.premiumIcon}>
          <Icon name="credit-card" size={24} color="#8b5cf6" />
        </View>
        <View style={styles.premiumInfo}>
          <Text style={styles.premiumAmount}>
            KES {parseFloat(item.premium_amount).toLocaleString()}
          </Text>
          <Text style={styles.premiumDate}>
            Due: {format(new Date(item.premium_due_date), 'dd MMM yyyy')}
          </Text>
        </View>
        <View style={[
          styles.statusBadge,
          item.payment_status === 'PAID' ? styles.statusPaid : styles.statusPending
        ]}>
          <Text style={styles.statusText}>{item.payment_status}</Text>
        </View>
      </View>
    </View>
  );

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

  return (
    <View style={styles.container}>
      <FlatList
        data={premiums}
        renderItem={renderPremium}
        keyExtractor={(item) => item.premium_id.toString()}
        contentContainerStyle={styles.listContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Icon name="credit-card-off" size={64} color="#9ca3af" />
            <Text style={styles.emptyText}>No premiums found</Text>
          </View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContent: {
    padding: 16,
  },
  premiumCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  premiumHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  premiumIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#ede9fe',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  premiumInfo: {
    flex: 1,
  },
  premiumAmount: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#8b5cf6',
  },
  premiumDate: {
    fontSize: 14,
    color: '#6b7280',
    marginTop: 4,
  },
  statusBadge: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 12,
  },
  statusPaid: {
    backgroundColor: '#d1fae5',
  },
  statusPending: {
    backgroundColor: '#fef3c7',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
    color: '#065f46',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 64,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 16,
  },
});
