/**
 * Withdrawal Request Screen
 * Request a new withdrawal
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
} 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 WithdrawalRequestScreen({ navigation }) {
  const [withdrawalType, setWithdrawalType] = useState('EARLY_EXIT');
  const [amount, setAmount] = useState('');
  const [reason, setReason] = useState('');
  const [loading, setLoading] = useState(false);

  const withdrawalTypes = [
    { value: 'EARLY_EXIT', label: 'Early Exit' },
    { value: 'RETIREMENT', label: 'Retirement' },
    { value: 'PARTIAL', label: 'Partial Withdrawal' },
  ];

  const handleSubmit = async () => {
    if (!amount || parseFloat(amount) <= 0) {
      Toast.show({
        type: 'error',
        text1: 'Validation Error',
        text2: 'Please enter a valid amount',
      });
      return;
    }

    if (!reason.trim()) {
      Toast.show({
        type: 'error',
        text1: 'Validation Error',
        text2: 'Please provide a reason for withdrawal',
      });
      return;
    }

    setLoading(true);
    try {
      const user = await AuthService.getCurrentUser();
      if (!user || !user.member_id) {
        throw new Error('User not found');
      }

      const response = await ApiService.post('/withdrawals', {
        member_id: user.member_id,
        withdrawal_type: withdrawalType,
        requested_amount: parseFloat(amount),
        reason: reason.trim(),
        requested_date: new Date().toISOString().split('T')[0],
      });

      if (response.success) {
        Alert.alert(
          'Success',
          'Withdrawal request submitted successfully. You will be notified once it is processed.',
          [
            {
              text: 'OK',
              onPress: () => navigation.goBack(),
            },
          ]
        );
      } else {
        throw new Error(response.message || 'Failed to submit withdrawal request');
      }
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: 'Error',
        text2: error.message || 'Failed to submit withdrawal request',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.card}>
        <Text style={styles.sectionTitle}>Withdrawal Type</Text>
        {withdrawalTypes.map((type) => (
          <TouchableOpacity
            key={type.value}
            style={[
              styles.typeOption,
              withdrawalType === type.value && styles.typeOptionSelected,
            ]}
            onPress={() => setWithdrawalType(type.value)}
          >
            <Icon
              name={withdrawalType === type.value ? 'radiobox-marked' : 'radiobox-blank'}
              size={24}
              color={withdrawalType === type.value ? '#2563eb' : '#9ca3af'}
            />
            <Text
              style={[
                styles.typeOptionText,
                withdrawalType === type.value && styles.typeOptionTextSelected,
              ]}
            >
              {type.label}
            </Text>
          </TouchableOpacity>
        ))}

        <View style={styles.inputGroup}>
          <Text style={styles.label}>Amount (KES)</Text>
          <TextInput
            style={styles.input}
            placeholder="Enter amount"
            value={amount}
            onChangeText={setAmount}
            keyboardType="numeric"
            editable={!loading}
          />
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>Reason</Text>
          <TextInput
            style={[styles.input, styles.textArea]}
            placeholder="Provide a reason for this withdrawal"
            value={reason}
            onChangeText={setReason}
            multiline
            numberOfLines={4}
            editable={!loading}
          />
        </View>

        <TouchableOpacity
          style={[styles.submitButton, loading && styles.submitButtonDisabled]}
          onPress={handleSubmit}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="#ffffff" />
          ) : (
            <>
              <Icon name="send" size={20} color="#ffffff" />
              <Text style={styles.submitButtonText}>Submit Request</Text>
            </>
          )}
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  card: {
    backgroundColor: '#ffffff',
    margin: 16,
    borderRadius: 12,
    padding: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1f2937',
    marginBottom: 16,
  },
  typeOption: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#e5e7eb',
    marginBottom: 12,
  },
  typeOptionSelected: {
    borderColor: '#2563eb',
    backgroundColor: '#eff6ff',
  },
  typeOptionText: {
    fontSize: 16,
    color: '#1f2937',
    marginLeft: 12,
  },
  typeOptionTextSelected: {
    color: '#2563eb',
    fontWeight: '600',
  },
  inputGroup: {
    marginTop: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    color: '#1f2937',
    marginBottom: 8,
  },
  input: {
    backgroundColor: '#f9fafb',
    borderWidth: 1,
    borderColor: '#e5e7eb',
    borderRadius: 12,
    padding: 16,
    fontSize: 16,
    color: '#1f2937',
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  submitButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#2563eb',
    padding: 16,
    borderRadius: 12,
    marginTop: 24,
  },
  submitButtonDisabled: {
    opacity: 0.6,
  },
  submitButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
    marginLeft: 8,
  },
});
