import { FlatList, RefreshControl, StatusBar, Text, TouchableOpacity, View } from 'react-native';
import { useApp } from '../context/AppContext';
import { useAuth } from '../context/AuthContext';
import styles from '../styles/index';

export function OrderList() {
  const {
    orders,
    selectedIds,
    setSelectedIds,
    setShowPickList,
    loading,
    fetchOrders,
    masterSettings,
    themeColor,
    duplicateNames,
    duplicateAddresses,
    setSelectedOrder,
    setSettingsTab,
    setSettingsVisible,
    staffName,
    setTempName,
    setShowLogin,
    staffList,
    authCompany,
  } = useApp();
  const { currentUser, securityMode } = useAuth();
  const switchableStaff = staffList.filter(s => {
    if (!s.is_active || s.role === 'master') return false;
    if (securityMode === 'individual_pin') return s.has_pin || !!s.pin_code;
    return securityMode === 'shared_honor';
  });
  const canSwitchUser = securityMode !== 'master_only' && switchableStaff.length > 0;
  const titleFromSlug = String(authCompany || '').trim()
    .replace(/[-_]+/g, ' ')
    .replace(/\b\w/g, c => c.toUpperCase());
  const warehouseTitle = String(masterSettings.warehouseDisplayName || '').trim() || titleFromSlug || 'Warehouse';
  const formatOrderDate = value => {
    if (!value) return '';
    const raw = String(value).trim();
    if (/^\d{1,2}:\d{2}\s+-\d{1,2}\/\d{1,2}\/\d{2}$/.test(raw)) return raw;
    let parsed = new Date(raw);
    if (Number.isNaN(parsed.getTime())) {
      const match = raw.match(/^([A-Za-z]{3,})\s+(\d{1,2}),\s+(\d{4})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?/);
      const months = {
        jan: 0, january: 0,
        feb: 1, february: 1,
        mar: 2, march: 2,
        apr: 3, april: 3,
        may: 4,
        jun: 5, june: 5,
        jul: 6, july: 6,
        aug: 7, august: 7,
        sep: 8, sept: 8, september: 8,
        oct: 9, october: 9,
        nov: 10, november: 10,
        dec: 11, december: 11,
      };
      if (match) {
        const month = months[match[1].toLowerCase()];
        if (month !== undefined) {
          parsed = new Date(
            Number(match[3]),
            month,
            Number(match[2]),
            Number(match[4]),
            Number(match[5]),
            Number(match[6] || 0)
          );
        }
      }
    }
    if (Number.isNaN(parsed.getTime())) return '';
    const hh = String(parsed.getHours()).padStart(2, '0');
    const mm = String(parsed.getMinutes()).padStart(2, '0');
    const dd = parsed.getDate();
    const mo = parsed.getMonth() + 1;
    const yy = String(parsed.getFullYear()).slice(-2);
    return `${hh}:${mm} -${dd}/${mo}/${yy}`;
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" backgroundColor={themeColor} />

      <View style={[styles.header, { backgroundColor: themeColor, alignItems: 'stretch', flexDirection: 'column', gap: 10 }]}>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <Text style={[styles.headerTitle, { flex: 1 }]} numberOfLines={1}>{warehouseTitle}</Text>
          <Text style={styles.headerCount}>{orders.length} Orders</Text>
        </View>

        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
          <TouchableOpacity
            style={{ flex: 1 }}
            disabled={!canSwitchUser}
            onPress={() => {
              if (!canSwitchUser) return;
              setTempName(staffName || currentUser?.name || '');
              setShowLogin(true);
            }}
          >
            <Text
              style={{ fontSize: 14, color: '#e1f3ed', textDecorationLine: canSwitchUser ? 'underline' : 'none' }}
              numberOfLines={1}
            >
              {staffName || currentUser?.name || 'Account'}
            </Text>
          </TouchableOpacity>
            <TouchableOpacity style={styles.refreshBtn} onPress={() => fetchOrders()}>
              <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 12 }}>REFRESH</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.refreshBtn}
              onPress={() => { setSettingsTab('general'); setSettingsVisible(true); }}
            >
              <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 12 }}>⚙️ SETTINGS</Text>
            </TouchableOpacity>
          </View>
      </View>

      <View style={styles.selectAllRow}>
        <View style={{ flex: 1 }}>
          {selectedIds.length > 0 && (
            <TouchableOpacity
              onPress={() => setShowPickList(true)}
              style={[styles.pickBtnSmall, { backgroundColor: themeColor }]}
            >
              <Text style={{ color: '#fff', fontWeight: 'bold' }}>Pick List ({selectedIds.length})</Text>
            </TouchableOpacity>
          )}
        </View>

        <TouchableOpacity
          style={{ flexDirection: 'row', alignItems: 'center' }}
          onPress={() => {
            if (selectedIds.length === orders.length) setSelectedIds([]);
            else setSelectedIds(orders.map(o => o.id));
          }}
        >
          <Text style={{ marginRight: 10, fontWeight: 'bold', color: '#666' }}>Select All</Text>
          <View
            style={
              selectedIds.length === orders.length
                ? [styles.radioOn, { backgroundColor: themeColor, borderColor: themeColor }]
                : styles.radioOff
            }
          />
        </TouchableOpacity>
      </View>

      <FlatList
        data={orders}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={{ paddingBottom: 110 }}
        renderItem={({ item }) => {
          const isAU = masterSettings.showInternationalWarning !== false && item.country === 'AU';
          const isSel = selectedIds.includes(item.id);
          const isPickup = item.is_pickup;

          const nameKey = (item.customer || '').trim().toLowerCase();
          const addrKey = (item.address || '').trim().toLowerCase();
          const isDuplicateName = nameKey.length > 2 && duplicateNames[nameKey] > 1;
          const isDuplicateAddr = addrKey.length > 5 && !isPickup && duplicateAddresses[addrKey] > 1;
          const isMergeable = isDuplicateName || isDuplicateAddr;
          const orderDateLabel = item.order_created_display || formatOrderDate(item.order_created_at || item.created_at || item.orderDate || item.order_date || item.importDate);

          return (
            <TouchableOpacity
              style={[
                styles.card,
                item.unpaid && styles.unpaidCard,
                isAU && styles.auCard,
                isPickup && styles.pickupCard,
                isSel && [styles.cardSel, { borderColor: themeColor }],
              ]}
              onPress={() => setSelectedOrder(item)}
            >
              <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                <View style={{ flex: 1, paddingRight: 10 }}>
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                    <View style={{ flexDirection: 'row', alignItems: 'baseline', flex: 1, minWidth: 0, marginRight: 8 }}>
                      <Text style={[styles.orderName, { flexShrink: 1 }]} numberOfLines={1}>
                        {item.name} {item.unpaid ? '(UNPAID)' : ''}
                        {!!orderDateLabel && (
                          <Text style={{ fontSize: 11, color: '#7b8794', fontWeight: '700' }}>
                            {'  '}{orderDateLabel}
                          </Text>
                        )}
                      </Text>
                    </View>
                    {isPickup ? null : (
                      <Text style={[styles.methodTextSm, { color: themeColor, maxWidth: '45%' }]} numberOfLines={1}>{item.method}</Text>
                    )}
                  </View>
                  <Text style={styles.customerText}>{item.customer}</Text>

                  {isAU && <Text style={styles.auText}>✈️ AUSTRALIA EXPORT</Text>}
                  {isPickup && <Text style={styles.pickupText}>🏪 CLICK & COLLECT</Text>}

                  {masterSettings.showRuralWarning && !isPickup && item.packie_status === 'RURAL' && (
                    <Text style={styles.ruralText}>🚜 RURAL DELIVERY</Text>
                  )}
                  {!isPickup && item.packie_status === 'INVALID' && (
                    <Text style={styles.invalidText}>❌ INVALID ADDRESS</Text>
                  )}
                  {!isPickup && item.packie_status === 'PENDING' && (
                    <Text style={styles.pendingText}>⏳ Validating Address...</Text>
                  )}

                  {masterSettings.showDoubleOrderWarning && isMergeable && (
                    <View style={styles.mergeWarningBox}>
                      <Text style={styles.mergeWarningText}>⚠️ MULTIPLE ORDERS: PACK TOGETHER</Text>
                    </View>
                  )}
                  {item.is_risky && (
                    <View style={styles.warningBoxSm}>
                      <Text style={styles.warningTextSm}>⚠️ HIGH RISK: CHECK SHOPIFY</Text>
                    </View>
                  )}
                  {item.needs_address_check && (
                    <View style={styles.warningBoxSm}>
                      <Text style={styles.warningTextSm}>⚠️ ADDRESS WARNING</Text>
                    </View>
                  )}

                  {item.note ? (
                    <View style={styles.mainNoteBox}>
                      <Text style={styles.mainNoteText}>📝 {item.note}</Text>
                    </View>
                  ) : null}
                </View>

                <TouchableOpacity
                  style={{ justifyContent: 'center', paddingLeft: 10 }}
                  onPress={() => {
                    if (isSel) setSelectedIds(selectedIds.filter(id => id !== item.id));
                    else setSelectedIds([...selectedIds, item.id]);
                  }}
                >
                  <View
                    style={
                      isSel
                        ? [styles.radioOn, { backgroundColor: themeColor, borderColor: themeColor }]
                        : styles.radioOff
                    }
                  />
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          );
        }}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={fetchOrders} tintColor={themeColor} />
        }
      />
    </View>
  );
}
