import { Alert, Modal, Text, TouchableOpacity, View } from 'react-native';
import { useApp } from '../context/AppContext';
import styles from '../styles/index';

export function QuantityModal() {
  const {
    qtyModalVisible,
    setQtyModalVisible,
    scannedItemData,
    scannedQty,
    setScannedQty,
    handlePickSingle,
    handlePickMaster,
    themeColor,
  } = useApp();

  const item = scannedItemData?.item;
  const remaining = scannedItemData?.remaining ?? 1;
  const type = scannedItemData?.type;

  return (
    <Modal visible={qtyModalVisible} transparent={true} animationType="fade">
      <View style={styles.modalOverlay}>
        <View style={styles.modalContent}>
          <Text style={{ fontSize: 20, fontWeight: 'bold', marginBottom: 10, textAlign: 'center' }}>Confirm Quantity</Text>
          <Text style={{ fontSize: 14, color: '#555', marginBottom: 20, textAlign: 'center' }}>{item?.name}</Text>
          <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 25 }}>
            <TouchableOpacity
              style={styles.qtyAdjustBtn}
              onPress={() => setScannedQty(prev => Math.max(1, prev - 1))}
            >
              <Text style={styles.qtyAdjustText}>-</Text>
            </TouchableOpacity>
            <Text style={{ fontSize: 36, fontWeight: 'bold', marginHorizontal: 30, color: themeColor }}>{scannedQty}</Text>
            <TouchableOpacity
              style={styles.qtyAdjustBtn}
              onPress={() => setScannedQty(prev => Math.min(remaining, prev + 1))}
            >
              <Text style={styles.qtyAdjustText}>+</Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={[styles.packBtn, { backgroundColor: themeColor }]}
            onPress={() => {
              if (!item) return;
              if (type === 'single') handlePickSingle(item.sku, item.qty, scannedQty);
              else handlePickMaster(item.sku, scannedQty);
              setQtyModalVisible(false);
              Alert.alert('Recorded', `Added ${scannedQty}x to the pick list.`);
            }}
          >
            <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>CONFIRM PICK</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );
}
