/**
 * Policies Screen
 * View life insurance policies
 */

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

export default function PoliciesScreen() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [policies, setPolicies] = useState([]);

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

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

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

  const getStatusColor = (status) => {
    switch (status) {
      case 'ACTIVE':
        return '#10b981';
      case 'LAPSED':
        return '#ef4444';
      case 'SURRENDERED':
        return '#6b7280';
      default:
        return '#6b7280';
    }
  };

  const renderPolicy = ({ item }) => (
    <TouchableOpacity
      style={styles.policyCard}
      onPress={() => navigation.navigate('PolicyDetails', { policy: item })}
    >
      <View style={styles.policyHeader}>
        <View style={styles.policyIcon}>
          <Icon name="shield-account" size={24} color="#3b82f6" />
        </View>
        <View style={styles.policyInfo}>
          <Text style={styles.policyNumber}>{item.policy_number}</Text>
          <Text style={styles.productName}>{item.product_name || 'Life Insurance'}</Text>
        </View>
        <View style={[styles.statusBadge, { backgroundColor: getStatusColor(item.policy_status) + '20' }]}>
          <Text style={[styles.statusText, { color: getStatusColor(item.policy_status) }]}>
            {item.policy_status}
          </Text>
        </View>
      </View>
      <View style={styles.policyDetails}>
        <View style={styles.detailItem}>
          <Text style={styles.detailLabel}>Sum Assured</Text>
          <Text style={styles.detailValue}>
            KES {parseFloat(item.sum_assured).toLocaleString()}
          </Text>
        </View>
        <View style={styles.detailItem}>
          <Text style={styles.detailLabel}>Premium</Text>
          <Text style={styles.detailValue}>
            KES {parseFloat(item.premium_amount).toLocaleString()}
          </Text>
        </View>
        <View style={styles.detailItem}>
          <Text style={styles.detailLabel}>Start Date</Text>
          <Text style={styles.detailValue}>
            {format(new Date(item.policy_start_date), 'dd MMM yyyy')}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );

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

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  listContent: {
    padding: 16,
  },
  policyCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  policyHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  policyIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#dbeafe',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  policyInfo: {
    flex: 1,
  },
  policyNumber: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
  },
  productName: {
    fontSize: 14,
    color: '#6b7280',
    marginTop: 4,
  },
  statusBadge: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 12,
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
  },
  policyDetails: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
  },
  detailItem: {
    flex: 1,
  },
  detailLabel: {
    fontSize: 12,
    color: '#6b7280',
    marginBottom: 4,
  },
  detailValue: {
    fontSize: 14,
    fontWeight: '600',
    color: '#1f2937',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 64,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 16,
  },
});
