import { Alert, FlatList, Image, KeyboardAvoidingView, Modal, Platform, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useEffect, useState } from 'react';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import { API_URL } from '../constants/defaults';
import { apiFetch } from '../services/api';
import styles from '../styles/index';

export function OrderDetail() {
  const {
    selectedOrder,
    closeOrder,
    lockInfo,
    editingNote,
    setEditingNote,
    saveNote,
    localOrderPicks,
    handlePickSingle,
    handleResetSingle,
    getSortedSingle,
    masterSettings,
    themeColor,
    isPending,
    isAUOrder,
    selectedOrderScannerAllowed,
    confirmPack,
    setAddressModalVisible,
    setIsScanning,
    staffName,
  } = useApp();
  const { effectiveCanPack, effectiveCanPick } = useAuth();
  const [showNoteEditor, setShowNoteEditor] = useState(false);

  useEffect(() => {
    setShowNoteEditor(false);
  }, [selectedOrder?.id]);

  if (!selectedOrder) return null;

  const addressText = selectedOrder?.corrected_address || selectedOrder?.address;
  const shippingMethodLabel = selectedOrder?.is_pickup
    ? 'CLICK & COLLECT (247 Cuba St)'
    : selectedOrder?.method;
  const shippingMethodColor = selectedOrder?.is_pickup ? '#8e44ad' : '#d73a49';
  const hasOrderNote = !!String(selectedOrder?.note || '').trim();
  const isInternationalOrder = String(selectedOrder?.country || '').trim().toUpperCase() !== ''
    && String(selectedOrder?.country || '').trim().toUpperCase() !== 'NZ';

  return (
    <Modal visible={selectedOrder !== null} animationType="slide">
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
        <View style={[styles.container, { paddingBottom: 40, paddingTop: 0 }]}>
          <View style={styles.modalHeader}>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', minWidth: 0, paddingRight: 12 }}>
              <Text style={styles.modalHeaderTitle} numberOfLines={1}>
                {selectedOrder?.name?.slice(0, -3)}
                <Text style={{ fontWeight: '900' }}>{selectedOrder?.name?.slice(-3)}</Text>
              </Text>
              <TouchableOpacity
                style={styles.noteToggleBtn}
                onPress={() => setShowNoteEditor(prev => !prev)}
              >
                <Text style={styles.noteToggleBtnText}>{hasOrderNote ? 'EDIT NOTE' : 'ADD NOTE'}</Text>
              </TouchableOpacity>
            </View>
            <TouchableOpacity onPress={closeOrder}>
              <Text style={{ fontSize: 24, color: '#333', padding: 5 }}>✕</Text>
            </TouchableOpacity>
          </View>

          <View style={{ padding: 20, flex: 1 }}>
            <Text style={{ fontWeight: 'bold', fontSize: 20, color: '#202223' }}>{selectedOrder?.customer}</Text>
            {addressText ? (
              <TouchableOpacity
                disabled={!masterSettings.allowAddressEditing}
                onPress={() => setAddressModalVisible(true)}
                activeOpacity={0.6}
                style={styles.addressTapArea}
              >
                <Text style={{ color: '#555', fontSize: 15 }}>{addressText}</Text>
                {selectedOrder?.postcode ? (
                  <Text style={{ color: '#111', fontWeight: 'bold', fontSize: 15, marginBottom: 0 }}>
                    {selectedOrder?.postcode}
                  </Text>
                ) : null}
              </TouchableOpacity>
            ) : selectedOrder?.postcode ? (
              <Text style={{ color: '#111', fontWeight: 'bold', fontSize: 15, marginBottom: 0 }}>
                {selectedOrder?.postcode}
              </Text>
            ) : null}

            <Text
              style={{
                color: shippingMethodColor,
                fontWeight: 'bold',
                marginBottom: 10,
                marginTop: 1,
                fontSize: 21,
              }}
            >
              {shippingMethodLabel}
            </Text>

            {isAUOrder && (
              <Text style={{ color: '#2196F3', fontWeight: 'bold', marginBottom: 10, fontSize: 18 }}>
                ✈️ AUSTRALIA EXPORT
              </Text>
            )}
            {lockInfo && (
              <View style={styles.lockBox}>
                <Text style={styles.lockText}>⚠️ {lockInfo} is packing this!</Text>
              </View>
            )}

            {hasOrderNote && !showNoteEditor ? (
              <View style={styles.mainNoteBox}>
                <Text style={styles.mainNoteText}>{selectedOrder.note}</Text>
              </View>
            ) : null}

            {showNoteEditor ? (
              <View style={styles.noteEditorBox}>
                <TextInput
                  style={styles.noteInput}
                  placeholder="Add order note..."
                  value={editingNote}
                  onChangeText={setEditingNote}
                  multiline
                />
                <TouchableOpacity
                  style={styles.saveNoteBtn}
                  onPress={async () => {
                    const ok = await saveNote();
                    if (ok) setShowNoteEditor(false);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold' }}>SAVE</Text>
                </TouchableOpacity>
              </View>
            ) : null}

            {isPending && !isInternationalOrder && (
              <View style={styles.validatingBox}>
                <Text style={styles.validatingText}>⏳ Validating Address with Packie...</Text>
              </View>
            )}

            {selectedOrder?.is_risky && (
              <View style={styles.warningBox}>
                <Text style={styles.warningBoxTitle}>⚠️ HIGH RISK ORDER</Text>
                <Text style={styles.warningBoxSub}>
                  {'Verify in Shopify. Remove the "Risk Warning" tag to unlock packing.'}
                </Text>
              </View>
            )}

            {selectedOrder?.needs_address_check && (
              <View style={styles.warningBox}>
                <Text style={styles.warningBoxTitle}>⚠️ SHOPIFY ADDRESS WARNING</Text>
                <Text style={styles.warningBoxSub}>
                  The address entered by the customer&apos;s checkout is invalid.
                </Text>
                {masterSettings.allowAddressEditing && (
                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: '#d35400', marginTop: 10, padding: 8 }]}
                    onPress={() => setAddressModalVisible(true)}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>FIX ADDRESS NOW</Text>
                  </TouchableOpacity>
                )}
              </View>
            )}

            {!selectedOrder?.is_pickup &&
              !isInternationalOrder &&
              ((selectedOrder?.packie_status === 'INVALID') ||
                (masterSettings.showRuralWarning && selectedOrder?.packie_status === 'RURAL')) && (
              <View style={styles.warningBox}>
                <Text style={styles.warningBoxTitle}>ADDRESS WARNING</Text>
                <Text style={styles.warningBoxSub}>
                  {selectedOrder.packie_status === 'RURAL'
                    ? 'Rural surcharge detected. Check or fix RD before printing.'
                    : 'Invalid address. Fix address before printing.'}
                </Text>
                {masterSettings.allowAddressEditing && (
                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: '#d35400', marginTop: 10, padding: 8 }]}
                    onPress={() => setAddressModalVisible(true)}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>EDIT ADDRESS / FIX RD</Text>
                  </TouchableOpacity>
                )}
              </View>
            )}

            <FlatList
              data={getSortedSingle(selectedOrder?.items || [])}
              keyExtractor={(item, index) => index.toString()}
              renderItem={({ item }) => {
                const count = localOrderPicks[item.sku]?.qty || 0;
                const isP = count >= item.qty;
                const stockLevel = item.stock_level !== undefined ? item.stock_level : null;
                const isLowStock =
                  masterSettings.showLowStockWarning &&
                  stockLevel !== null &&
                  stockLevel <= masterSettings.lowStockThreshold;

                return (
                  <TouchableOpacity
                    style={[styles.itemRow, isP && styles.itemPicked]}
                    pressRetentionOffset={{ top: 20, left: 20, right: 20, bottom: 20 }}
                    onPress={effectiveCanPick ? () => handlePickSingle(item.sku, item.qty) : null}
                    onLongPress={effectiveCanPick ? () => handleResetSingle(item.sku) : null}
                    disabled={!effectiveCanPick}
                    delayPressIn={0}
                  >
                    {masterSettings.showProductImages ? (
                      <Image source={{ uri: item.img }} style={styles.thumb} />
                    ) : null}
                    <View style={{ flex: 1 }}>
                      <Text style={[styles.itemName, isP && styles.strikethrough]}>{item.name}</Text>
                      <Text style={{ fontSize: 12, color: '#666' }}>{item.sku}</Text>
                      {isLowStock && (
                        <Text style={styles.lowStockWarning}>⚠️ Only {stockLevel} left in stock!</Text>
                      )}
                    </View>
                    <View
                      style={[
                        styles.qtyBadge,
                        isP ? [styles.qtyBadgeDone, { backgroundColor: themeColor }] : styles.qtyBadgePending,
                      ]}
                    >
                      <Text style={[styles.itemQty, { color: themeColor }, isP && { color: '#fff' }]}>
                        {count} / {item.qty}
                      </Text>
                    </View>
                  </TouchableOpacity>
                );
              }}
            />

            <View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 10, marginTop: 10 }}>
              {masterSettings.enableScanner && (
                <TouchableOpacity
                  style={[
                    styles.packBtn,
                    { flex: 1, backgroundColor: selectedOrderScannerAllowed && effectiveCanPick ? '#007ace' : '#95a5a6' },
                  ]}
                  onPress={() => {
                    if (!effectiveCanPick) {
                      Alert.alert('Pick Access', 'Your account does not have pick access.');
                      return;
                    }
                    if (!selectedOrderScannerAllowed) {
                      Alert.alert('Scanner Disabled', 'This order has items without SKU. Pick by name instead.');
                      return;
                    }
                    setIsScanning(true);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>SCAN ITEM</Text>
                </TouchableOpacity>
              )}

              {lockInfo ? (
                <TouchableOpacity
                  style={[styles.packBtn, { backgroundColor: effectiveCanPack ? '#c0392b' : '#ccc', flex: 1 }]}
                  onPress={effectiveCanPack ? confirmPack : null}
                  disabled={!effectiveCanPack}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>
                    {effectiveCanPack ? '⚠️ OVERRIDE LOCK' : '🔒 NO PACK ACCESS'}
                  </Text>
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  style={[
                    styles.packBtn,
                    { backgroundColor: effectiveCanPack ? themeColor : '#ccc', flex: 1 },
                    ((isPending && !isInternationalOrder) || selectedOrder?.is_risky || selectedOrder?.needs_address_check) && effectiveCanPack && {
                      backgroundColor: '#ccc',
                    },
                  ]}
                  onPress={effectiveCanPack ? () => {
                    try {
                      console.log('[mark_packed click]', {
                        isPending,
                        packie_status: selectedOrder?.packie_status,
                        is_risky: selectedOrder?.is_risky,
                        needs_address_check: selectedOrder?.needs_address_check,
                        selectedOrderId: selectedOrder?.id,
                        staff: staffName,
                      });
                    } catch (e) { console.warn('log error', e); }
                    try {
                      apiFetch(API_URL, {
                        method: 'POST',
                        body: JSON.stringify({
                          action: 'client_click_log',
                          order_id: selectedOrder?.id ?? null,
                          order_name: selectedOrder?.name ?? null,
                          isPending: !!isPending,
                          packie_status: selectedOrder?.packie_status ?? null,
                          is_risky: !!selectedOrder?.is_risky,
                          needs_address_check: !!selectedOrder?.needs_address_check,
                          staff: staffName,
                          ts: new Date().toISOString(),
                        }),
                      }).catch(e => console.warn('client_log send failed', e));
                    } catch (e) {
                      console.warn('client_log error', e);
                    }
                    if (isPending && !isInternationalOrder) {
                      Alert.alert(
                        'Still Validating',
                        'Address is still being checked by Packie. Please wait a moment and try again.'
                      );
                      return;
                    }
                    if (selectedOrder?.is_risky) {
                      Alert.alert(
                        'High Risk Order',
                        "This order is flagged as high risk. Remove the 'Risk Warning' tag in Shopify to enable packing, or press OK to pack anyway.",
                        [
                          { text: 'Cancel', style: 'cancel' },
                          { text: 'Pack Anyway', style: 'destructive', onPress: confirmPack },
                        ]
                      );
                      return;
                    }
                    if (selectedOrder?.needs_address_check) {
                      Alert.alert(
                        'Address Warning',
                        "The customer's address may be invalid. Check and correct it first, or press OK to pack anyway.",
                        [
                          { text: 'Cancel', style: 'cancel' },
                          { text: 'Pack Anyway', style: 'destructive', onPress: confirmPack },
                        ]
                      );
                      return;
                    }
                    confirmPack();
                  } : null}
                  activeOpacity={0.2}
                  disabled={!effectiveCanPack}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>
                    {effectiveCanPack ? 'MARK PACKED' : '🔒 NO PACK ACCESS'}
                  </Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
