/**
 * Dashboard Screen
 * Main dashboard with account summary and quick actions
 */

import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  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';

export default function DashboardScreen() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [user, setUser] = useState(null);
  const [balance, setBalance] = useState(null);
  const [stats, setStats] = useState({
    totalContributions: 0,
    totalWithdrawals: 0,
    activePolicies: 0,
    pendingWithdrawals: 0,
  });

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

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      const currentUser = await AuthService.getCurrentUser();
      setUser(currentUser);

      if (currentUser && currentUser.member_id) {
        // Load balance
        const balanceResponse = await MemberService.getBalance(currentUser.member_id);
        if (balanceResponse.success) {
          setBalance(balanceResponse.data);
        }

        // Load dashboard stats
        const statsResponse = await ApiService.get('/analytics/dashboard', {
          member_id: currentUser.member_id,
        });
        if (statsResponse.success) {
          setStats(statsResponse.data);
        }
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: 'Failed to load dashboard data',
      });
    } finally {
      setLoading(false);
    }
  };

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

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

  return (
    <ScrollView
      style={styles.container}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
    >
      {/* Welcome Header */}
      <View style={styles.header}>
        <View>
          <Text style={styles.greeting}>Welcome back,</Text>
          <Text style={styles.name}>{user?.username || 'Member'}</Text>
        </View>
        <TouchableOpacity
          onPress={() => navigation.navigate('Profile')}
          style={styles.profileButton}
        >
          <Icon name="account-circle" size={40} color="#2563eb" />
        </TouchableOpacity>
      </View>

      {/* Account Balance Card */}
      <View style={styles.balanceCard}>
        <Text style={styles.balanceLabel}>Total Account Balance</Text>
        <Text style={styles.balanceAmount}>
          KES {balance?.total_balance?.toLocaleString() || '0.00'}
        </Text>
        <View style={styles.balanceDetails}>
          <View style={styles.balanceItem}>
            <Text style={styles.balanceItemLabel}>Employee Contributions</Text>
            <Text style={styles.balanceItemValue}>
              KES {balance?.total_employee_contributions?.toLocaleString() || '0.00'}
            </Text>
          </View>
          <View style={styles.balanceItem}>
            <Text style={styles.balanceItemLabel}>Employer Contributions</Text>
            <Text style={styles.balanceItemValue}>
              KES {balance?.total_employer_contributions?.toLocaleString() || '0.00'}
            </Text>
          </View>
          <View style={styles.balanceItem}>
            <Text style={styles.balanceItemLabel}>Investment Returns</Text>
            <Text style={styles.balanceItemValue}>
              KES {balance?.total_investment_returns?.toLocaleString() || '0.00'}
            </Text>
          </View>
        </View>
      </View>

      {/* Quick Stats */}
      <View style={styles.statsContainer}>
        <View style={styles.statCard}>
          <Icon name="wallet" size={32} color="#10b981" />
          <Text style={styles.statValue}>{stats.totalContributions}</Text>
          <Text style={styles.statLabel}>Contributions</Text>
        </View>
        <View style={styles.statCard}>
          <Icon name="cash-multiple" size={32} color="#f59e0b" />
          <Text style={styles.statValue}>{stats.totalWithdrawals}</Text>
          <Text style={styles.statLabel}>Withdrawals</Text>
        </View>
        <View style={styles.statCard}>
          <Icon name="shield-account" size={32} color="#3b82f6" />
          <Text style={styles.statValue}>{stats.activePolicies}</Text>
          <Text style={styles.statLabel}>Active Policies</Text>
        </View>
        <View style={styles.statCard}>
          <Icon name="clock-outline" size={32} color="#ef4444" />
          <Text style={styles.statValue}>{stats.pendingWithdrawals}</Text>
          <Text style={styles.statLabel}>Pending</Text>
        </View>
      </View>

      {/* Quick Actions */}
      <View style={styles.quickActions}>
        <Text style={styles.sectionTitle}>Quick Actions</Text>
        <View style={styles.actionsGrid}>
          <TouchableOpacity
            style={styles.actionCard}
            onPress={() => navigation.navigate('WithdrawalRequest')}
          >
            <Icon name="cash-fast" size={32} color="#2563eb" />
            <Text style={styles.actionText}>Request Withdrawal</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.actionCard}
            onPress={() => navigation.navigate('Statement')}
          >
            <Icon name="file-document" size={32} color="#10b981" />
            <Text style={styles.actionText}>View Statement</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.actionCard}
            onPress={() => navigation.navigate('Beneficiaries')}
          >
            <Icon name="account-group" size={32} color="#f59e0b" />
            <Text style={styles.actionText}>Beneficiaries</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.actionCard}
            onPress={() => navigation.navigate('Premiums')}
          >
            <Icon name="credit-card" size={32} color="#8b5cf6" />
            <Text style={styles.actionText}>Pay Premium</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* Recent Activity */}
      <View style={styles.recentActivity}>
        <Text style={styles.sectionTitle}>Recent Activity</Text>
        <View style={styles.activityItem}>
          <Icon name="wallet" size={24} color="#10b981" />
          <View style={styles.activityContent}>
            <Text style={styles.activityTitle}>Contribution Posted</Text>
            <Text style={styles.activityDate}>2 days ago</Text>
          </View>
          <Text style={styles.activityAmount}>KES 5,000</Text>
        </View>
        <View style={styles.activityItem}>
          <Icon name="cash-multiple" size={24} color="#f59e0b" />
          <View style={styles.activityContent}>
            <Text style={styles.activityTitle}>Withdrawal Processed</Text>
            <Text style={styles.activityDate}>1 week ago</Text>
          </View>
          <Text style={styles.activityAmount}>KES 10,000</Text>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#ffffff',
  },
  greeting: {
    fontSize: 14,
    color: '#6b7280',
  },
  name: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#1f2937',
    marginTop: 4,
  },
  profileButton: {
    padding: 8,
  },
  balanceCard: {
    backgroundColor: '#2563eb',
    margin: 20,
    padding: 24,
    borderRadius: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  balanceLabel: {
    color: '#ffffff',
    fontSize: 14,
    opacity: 0.9,
  },
  balanceAmount: {
    color: '#ffffff',
    fontSize: 32,
    fontWeight: 'bold',
    marginTop: 8,
  },
  balanceDetails: {
    marginTop: 20,
    paddingTop: 20,
    borderTopWidth: 1,
    borderTopColor: 'rgba(255, 255, 255, 0.2)',
  },
  balanceItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 12,
  },
  balanceItemLabel: {
    color: '#ffffff',
    fontSize: 14,
    opacity: 0.9,
  },
  balanceItemValue: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: '600',
  },
  statsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 20,
    marginBottom: 20,
  },
  statCard: {
    width: '48%',
    backgroundColor: '#ffffff',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
    marginRight: '2%',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  statValue: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#1f2937',
    marginTop: 8,
  },
  statLabel: {
    fontSize: 12,
    color: '#6b7280',
    marginTop: 4,
  },
  quickActions: {
    paddingHorizontal: 20,
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#1f2937',
    marginBottom: 16,
  },
  actionsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  actionCard: {
    width: '48%',
    backgroundColor: '#ffffff',
    padding: 20,
    borderRadius: 12,
    marginBottom: 12,
    marginRight: '2%',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  actionText: {
    fontSize: 14,
    color: '#1f2937',
    marginTop: 8,
    textAlign: 'center',
  },
  recentActivity: {
    paddingHorizontal: 20,
    marginBottom: 20,
  },
  activityItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
  },
  activityContent: {
    flex: 1,
    marginLeft: 12,
  },
  activityTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: '#1f2937',
  },
  activityDate: {
    fontSize: 12,
    color: '#6b7280',
    marginTop: 4,
  },
  activityAmount: {
    fontSize: 16,
    fontWeight: '600',
    color: '#10b981',
  },
});
