/**
 * Withdrawals Screen
 * View withdrawal history and request new withdrawals
 */

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 WithdrawalsScreen() {
  const navigation = useNavigation();
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [withdrawals, setWithdrawals] = useState([]);

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

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

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

  const getStatusColor = (status) => {
    switch (status) {
      case 'APPROVED':
        return '#10b981';
      case 'PENDING':
        return '#f59e0b';
      case 'REJECTED':
        return '#ef4444';
      case 'PROCESSED':
        return '#3b82f6';
      default:
        return '#6b7280';
    }
  };

  const renderWithdrawal = ({ item }) => (
    <TouchableOpacity style={styles.withdrawalCard}>
      <View style={styles.withdrawalHeader}>
        <View style={styles.withdrawalIcon}>
          <Icon name="cash-multiple" size={24} color="#f59e0b" />
        </View>
        <View style={styles.withdrawalInfo}>
          <Text style={styles.withdrawalType}>{item.withdrawal_type}</Text>
          <Text style={styles.withdrawalDate}>
            {format(new Date(item.requested_date), 'dd MMM yyyy')}
          </Text>
        </View>
        <View style={styles.withdrawalAmount}>
          <Text style={styles.amount}>KES {parseFloat(item.requested_amount).toLocaleString()}</Text>
          <View style={[styles.statusBadge, { backgroundColor: getStatusColor(item.status) + '20' }]}>
            <Text style={[styles.statusText, { color: getStatusColor(item.status) }]}>
              {item.status}
            </Text>
          </View>
        </View>
      </View>
      {item.reason && (
        <View style={styles.withdrawalFooter}>
          <Text style={styles.reason}>{item.reason}</Text>
        </View>
      )}
    </TouchableOpacity>
  );

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

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.requestButton}
        onPress={() => navigation.navigate('WithdrawalRequest')}
      >
        <Icon name="plus-circle" size={24} color="#ffffff" />
        <Text style={styles.requestButtonText}>Request Withdrawal</Text>
      </TouchableOpacity>

      <FlatList
        data={withdrawals}
        renderItem={renderWithdrawal}
        keyExtractor={(item) => item.withdrawal_request_id.toString()}
        contentContainerStyle={styles.listContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Icon name="cash-off" size={64} color="#9ca3af" />
            <Text style={styles.emptyText}>No withdrawals found</Text>
            <Text style={styles.emptySubtext}>Tap the button above to request a withdrawal</Text>
          </View>
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  requestButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#2563eb',
    margin: 16,
    padding: 16,
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  requestButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
    marginLeft: 8,
  },
  listContent: {
    padding: 16,
    paddingTop: 0,
  },
  withdrawalCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  withdrawalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  withdrawalIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#fef3c7',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  withdrawalInfo: {
    flex: 1,
  },
  withdrawalType: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
  },
  withdrawalDate: {
    fontSize: 14,
    color: '#6b7280',
    marginTop: 4,
  },
  withdrawalAmount: {
    alignItems: 'flex-end',
  },
  amount: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#f59e0b',
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
    marginTop: 4,
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
  },
  withdrawalFooter: {
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
  },
  reason: {
    fontSize: 14,
    color: '#6b7280',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 64,
  },
  emptyText: {
    fontSize: 16,
    color: '#9ca3af',
    marginTop: 16,
    fontWeight: '600',
  },
  emptySubtext: {
    fontSize: 14,
    color: '#9ca3af',
    marginTop: 8,
    textAlign: 'center',
  },
});
