import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { router } from 'expo-router';
import { api } from '../../../services/api';

export default function SubmitRemittanceScreen() {
  const [amount, setAmount] = useState('');
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async () => {
    if (!amount || isNaN(Number(amount))) return Alert.alert('Required', 'Enter a valid amount.');
    setLoading(true);
    try {
      await api.post('/api/v1/remittances', { totalAmount: Number(amount), notes });
      Alert.alert('Submitted', 'Remittance submitted successfully.', [{ text: 'OK', onPress: () => router.back() }]);
    } catch (e: any) {
      Alert.alert('Error', e?.response?.data?.message ?? 'Submission failed.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-4 bg-primary flex-row items-center">
        <TouchableOpacity onPress={() => router.back()} className="mr-3">
          <Text className="text-white text-lg">←</Text>
        </TouchableOpacity>
        <Text className="text-white text-xl font-bold">Submit Remittance</Text>
      </View>
      <ScrollView className="flex-1 px-4 py-6">
        <Text className="font-semibold text-gray-700 mb-2">Total Collection (₱)</Text>
        <TextInput
          className="bg-white border border-gray-200 rounded-xl px-4 py-3 text-base mb-4"
          placeholder="0.00"
          value={amount}
          onChangeText={setAmount}
          keyboardType="numeric"
          autoFocus
        />
        <Text className="font-semibold text-gray-700 mb-2">Notes (optional)</Text>
        <TextInput
          className="bg-white border border-gray-200 rounded-xl px-4 py-3 text-base mb-8"
          placeholder="Any remarks..."
          value={notes}
          onChangeText={setNotes}
          multiline
          numberOfLines={3}
        />
        <TouchableOpacity className="bg-primary rounded-xl py-4 items-center" onPress={submit} disabled={loading}>
          {loading ? <ActivityIndicator color="white" /> : <Text className="text-white font-bold text-base">Submit Remittance</Text>}
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
}
