import {
  Alert,
  FlatList,
  KeyboardAvoidingView,
  Linking,
  Modal,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { useEffect, useState } from 'react';
import { useApp } from '../context/AppContext';
import styles from '../styles/index';

const COUNTRY_OPTIONS = [
  ['NZ', 'New Zealand'], ['AU', 'Australia'], ['CN', 'China'], ['US', 'United States'], ['GB', 'United Kingdom'],
  ['CA', 'Canada'], ['ZA', 'South Africa'], ['IN', 'India'], ['PH', 'Philippines'], ['FJ', 'Fiji'],
  ['WS', 'Samoa'], ['TO', 'Tonga'], ['CK', 'Cook Islands'], ['JP', 'Japan'], ['KR', 'South Korea'],
  ['SG', 'Singapore'], ['HK', 'Hong Kong'], ['MY', 'Malaysia'], ['TH', 'Thailand'], ['VN', 'Vietnam'],
  ['ID', 'Indonesia'], ['TW', 'Taiwan'], ['AE', 'United Arab Emirates'], ['AF', 'Afghanistan'], ['AL', 'Albania'],
  ['DZ', 'Algeria'], ['AD', 'Andorra'], ['AO', 'Angola'], ['AR', 'Argentina'], ['AM', 'Armenia'],
  ['AT', 'Austria'], ['AZ', 'Azerbaijan'], ['BS', 'Bahamas'], ['BH', 'Bahrain'], ['BD', 'Bangladesh'],
  ['BB', 'Barbados'], ['BE', 'Belgium'], ['BZ', 'Belize'], ['BJ', 'Benin'], ['BM', 'Bermuda'],
  ['BT', 'Bhutan'], ['BO', 'Bolivia'], ['BA', 'Bosnia and Herzegovina'], ['BW', 'Botswana'], ['BR', 'Brazil'],
  ['BN', 'Brunei'], ['BG', 'Bulgaria'], ['KH', 'Cambodia'], ['CM', 'Cameroon'], ['CL', 'Chile'],
  ['CO', 'Colombia'], ['CR', 'Costa Rica'], ['HR', 'Croatia'], ['CY', 'Cyprus'], ['CZ', 'Czechia'],
  ['DK', 'Denmark'], ['DO', 'Dominican Republic'], ['EC', 'Ecuador'], ['EG', 'Egypt'], ['EE', 'Estonia'],
  ['FI', 'Finland'], ['FR', 'France'], ['DE', 'Germany'], ['GH', 'Ghana'], ['GR', 'Greece'],
  ['GL', 'Greenland'], ['GT', 'Guatemala'], ['GY', 'Guyana'], ['HU', 'Hungary'], ['IS', 'Iceland'],
  ['IE', 'Ireland'], ['IL', 'Israel'], ['IT', 'Italy'], ['JM', 'Jamaica'], ['KE', 'Kenya'],
  ['KW', 'Kuwait'], ['LA', 'Laos'], ['LV', 'Latvia'], ['LB', 'Lebanon'], ['LT', 'Lithuania'],
  ['LU', 'Luxembourg'], ['MO', 'Macau'], ['MG', 'Madagascar'], ['MV', 'Maldives'], ['MT', 'Malta'],
  ['MU', 'Mauritius'], ['MX', 'Mexico'], ['MN', 'Mongolia'], ['MA', 'Morocco'], ['MM', 'Myanmar'],
  ['NP', 'Nepal'], ['NL', 'Netherlands'], ['NC', 'New Caledonia'], ['NG', 'Nigeria'], ['NO', 'Norway'],
  ['OM', 'Oman'], ['PK', 'Pakistan'], ['PG', 'Papua New Guinea'], ['PE', 'Peru'], ['PL', 'Poland'],
  ['PT', 'Portugal'], ['QA', 'Qatar'], ['RO', 'Romania'], ['SA', 'Saudi Arabia'], ['RS', 'Serbia'],
  ['SC', 'Seychelles'], ['LK', 'Sri Lanka'], ['ES', 'Spain'], ['SE', 'Sweden'], ['CH', 'Switzerland'],
  ['TR', 'Turkey'], ['UG', 'Uganda'], ['UA', 'Ukraine'], ['UY', 'Uruguay'], ['VU', 'Vanuatu'],
  ['ZM', 'Zambia'], ['ZW', 'Zimbabwe'],
].sort((a, b) => a[1].localeCompare(b[1]));

export function LabelModal() {
  const {
    labelModalVisible,
    setLabelModalVisible,
    getSortedStocks,
    getSortedLiveStocks,
    selectedStockId,
    setSelectedStockId,
    customDims,
    setCustomDims,
    customQuotes,
    setCustomQuotes,
    satchelQuotes,
    setSatchelQuotes,
    satchelQuoteErrors,
    setSatchelQuoteErrors,
    satchelQuoteProviders,
    setSatchelQuoteProviders,
    isFetchingQuotes,
    isFetchingSatchelQuotes,
    handleFinalPackAndPrint,
    handleGetQuotes,
    handleGetSatchelQuotes,
    forceOverrideRef,
    themeColor,
    selectedOrder,
  } = useApp();
  const [labelMode, setLabelMode] = useState('quick');
  const [internationalDetails, setInternationalDetails] = useState(null);
  const [customsSectionOpen, setCustomsSectionOpen] = useState(true);
  const [invoiceSectionOpen, setInvoiceSectionOpen] = useState(true);
  const [descriptionDropdownOpen, setDescriptionDropdownOpen] = useState(false);
  const [originDropdownIndex, setOriginDropdownIndex] = useState(null);
  const [originSearch, setOriginSearch] = useState('');
  const orderAddress = String(selectedOrder?.original_address || selectedOrder?.address || '').trim();
  const orderCountry = String(selectedOrder?.country || '').trim().toUpperCase();
  const isInternational = orderCountry !== '' && orderCountry !== 'NZ';
  const getOrderEmail = order => String(order?.email || order?.receiver_email || '').trim();
  const quickPrintStocks = getSortedStocks();
  const livePricingStocks = getSortedLiveStocks();
  const hasQuickPrintStocks = quickPrintStocks.length > 0;
  const initialLabelMode = isInternational ? 'custom' : (hasQuickPrintStocks ? 'quick' : 'live');
  const activeStockList = labelMode === 'live' ? livePricingStocks : quickPrintStocks;
  const descriptionOptions = [
    ['0', 'Gift'],
    ['1', 'Sale of Goods'],
    ['2', 'Commercial'],
    ['3', 'Returned Goods'],
    ['4', 'Document'],
    ['5', 'Other'],
  ];
  const selectedDescriptionLabel = descriptionOptions.find(([value]) => value === internationalDetails?.detailedDescription)?.[1]
    || internationalDetails?.detailedDescriptionLabel
    || 'Sale of Goods';
  const getCountryName = code => COUNTRY_OPTIONS.find(([value]) => value === String(code || '').toUpperCase())?.[1] || String(code || 'Select country');
  const filteredCountryOptions = COUNTRY_OPTIONS.filter(([, name]) =>
    name.toLowerCase().includes(originSearch.trim().toLowerCase())
  ).slice(0, 40);
  const numericString = value => {
    const parsed = parseFloat(value);
    return Number.isFinite(parsed) && parsed > 0 ? String(parsed) : '';
  };
  const todayIso = () => {
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
  };
  const orderNumber = String(selectedOrder?.name || '').replace(/^#/, '');
  const defaultInternationalItems = order => {
    const items = Array.isArray(order?.items) ? order.items : [];
    return items.map(item => ({
      description: String(item?.name || 'Goods').slice(0, 50),
      quantity: String(item?.qty || 1),
      netWeight: numericString(item?.weight) || '0.001',
      value: numericString(item?.price) || '1.00',
      countryOfOrigin: String(item?.countryOfOrigin || item?.country_of_origin || 'CN').toUpperCase(),
      hsTariff: String(item?.hsCode || item?.hs_code || ''),
    }));
  };
  const buildDefaultInternationalDetails = order => ({
    detailedDescription: '1',
    detailedDescriptionLabel: 'Sale of Goods',
    otherDescription: '',
    receiverTaxNo: '',
    receiverEmail: getOrderEmail(order),
    currency: 'NZD',
    reference: String(order?.name || '').replace(/^#/, ''),
    date: todayIso(),
    items: defaultInternationalItems(order),
    signatureRequired: false,
  });
  const updateInternationalDetails = patch => {
    setInternationalDetails(prev => ({ ...(prev || buildDefaultInternationalDetails(selectedOrder)), ...patch }));
  };
  const updateInternationalItem = (index, patch) => {
    setInternationalDetails(prev => {
      const base = prev || buildDefaultInternationalDetails(selectedOrder);
      const items = [...(base.items || [])];
      items[index] = { ...(items[index] || {}), ...patch };
      return { ...base, items };
    });
  };
  const normalizeInternationalDetails = () => {
    if (!isInternational) return null;
    const details = internationalDetails || buildDefaultInternationalDetails(selectedOrder);
    const items = (details.items || []).map(item => ({
      description: String(item.description || 'Goods').trim().slice(0, 50),
      quantity: Math.max(1, parseInt(item.quantity, 10) || 1),
      netWeight: parseFloat(item.netWeight) || 0,
      value: parseFloat(item.value) || 0,
      countryOfOrigin: String(item.countryOfOrigin || 'CN').trim().toUpperCase(),
      hsTariff: String(item.hsTariff || '').replace(/\D/g, '').trim(),
    }));
    return {
      ...details,
      receiverEmail: String(details.receiverEmail || '').trim(),
      currency: String(details.currency || 'NZD').trim().toUpperCase(),
      reference: String(details.reference || orderNumber).trim().slice(0, 50),
      date: String(details.date || todayIso()).trim(),
      items,
      totalWeight: items.reduce((sum, item) => sum + item.netWeight * item.quantity, 0),
      totalDeclaredAmount: items.reduce((sum, item) => sum + item.value * item.quantity, 0),
      destinationCountry: orderCountry,
    };
  };
  const getInternationalError = details => {
    if (!isInternational) return '';
    if (!details?.detailedDescription) return 'Choose the detailed description.';
    if (details.detailedDescription === '5' && !String(details.otherDescription || '').trim()) return 'Specify the other description.';
    if (!String(details.receiverEmail || '').trim()) return 'Enter the receiver email address.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(details.receiverEmail || '').trim())) return 'Enter a valid receiver email address.';
    if (!details.date) return 'Enter the invoice date.';
    if (!Array.isArray(details.items) || details.items.length === 0) return 'Add at least one invoice item.';
    for (const item of details.items) {
      if (!item.description) return 'Each invoice line needs a description.';
      if (!(item.quantity > 0)) return 'Each invoice line needs a quantity.';
      if (!(item.netWeight > 0)) return 'Each invoice line needs a net weight.';
      if (!(item.value > 0)) return 'Each invoice line needs a declared value.';
      if (!item.countryOfOrigin) return 'Each invoice line needs a country of origin.';
      if (!item.hsTariff || item.hsTariff.length < 6) return 'Each invoice line needs an HS tariff number of at least 6 digits.';
    }
    return '';
  };
  const requireInternationalDetails = () => {
    const details = normalizeInternationalDetails();
    const error = getInternationalError(details);
    if (error) {
      Alert.alert('International Details', error);
      return null;
    }
    return details;
  };
  const submitPrintAndPack = (stockId, rate) => {
    const details = requireInternationalDetails();
    if (isInternational && !details) return;
    handleFinalPackAndPrint(stockId, rate, forceOverrideRef.current, details);
  };

  useEffect(() => {
    if (!labelModalVisible) return;
    setLabelMode(initialLabelMode);
    setInternationalDetails(isInternational ? buildDefaultInternationalDetails(selectedOrder) : null);
    setOriginDropdownIndex(null);
    setOriginSearch('');
    setSatchelQuotes([]);
    setSatchelQuoteErrors([]);
    setSatchelQuoteProviders([]);
  }, [initialLabelMode, isInternational, labelModalVisible, selectedOrder?.id, setSatchelQuoteErrors, setSatchelQuoteProviders, setSatchelQuotes]);

  useEffect(() => {
    if (!labelModalVisible || isInternational || labelMode !== 'quick' || hasQuickPrintStocks) return;
    setLabelMode('live');
    setSatchelQuotes([]);
    setSatchelQuoteErrors([]);
    setSatchelQuoteProviders([]);
  }, [hasQuickPrintStocks, isInternational, labelMode, labelModalVisible, setSatchelQuoteErrors, setSatchelQuoteProviders, setSatchelQuotes]);

  useEffect(() => {
    if (!labelModalVisible || labelMode === 'custom') return;
    if (!activeStockList.some(item => String(item.id) === String(selectedStockId))) {
      setSelectedStockId(activeStockList[0]?.id || null);
      setSatchelQuotes([]);
      setSatchelQuoteErrors([]);
      setSatchelQuoteProviders([]);
    }
  }, [activeStockList, labelMode, labelModalVisible, selectedStockId, setSatchelQuoteErrors, setSatchelQuoteProviders, setSatchelQuotes, setSelectedStockId]);
  const toMoneyNumber = value => {
    const parsed = parseFloat(value);
    return Number.isFinite(parsed) ? parsed : 0;
  };
  const getQuoteParcels = item => Array.isArray(item?.parcels) ? item.parcels : [];
  const getQuoteBasePrice = item => {
    const parcels = getQuoteParcels(item);
    if (parcels.length > 0) return parcels.reduce((sum, parcel) => sum + toMoneyNumber(parcel?.rate), 0);
    return toMoneyNumber(item?.rate ?? item?.price);
  };
  const quoteExtraKeys = [
    ['residentialCost', 'Residential'],
    ['rural_rate', 'Rural'],
    ['dangerousgoods_rate', 'Dangerous goods'],
    ['longlength_rate', 'Long length'],
    ['otherCost', 'Other'],
    ['fuelSurchargeAmount', 'Fuel'],
  ];
  const getQuoteExtras = item => {
    const totals = {};
    getQuoteParcels(item).forEach(parcel => {
      quoteExtraKeys.forEach(([key, label]) => {
        totals[label] = (totals[label] || 0) + toMoneyNumber(parcel?.[key]);
      });
    });
    quoteExtraKeys.forEach(([key, label]) => {
      const topLevel = toMoneyNumber(item?.[key]);
      if (topLevel > 0 && !(totals[label] > 0)) totals[label] = topLevel;
    });
    const ruralProvider = toMoneyNumber(item?.ruralRateChargedByProvider);
    if (ruralProvider > 0 && !(totals.Rural > 0)) totals.Rural = ruralProvider;
    return Object.entries(totals).filter(([, amount]) => amount > 0);
  };
  const getQuotePrice = item => getQuoteBasePrice(item) + getQuoteExtras(item).reduce((sum, [, amount]) => sum + amount, 0);
  const formatQuotePrice = item => {
    const parsed = getQuotePrice(item);
    return Number.isFinite(parsed) ? parsed.toFixed(2) : '0.00';
  };
  const formatQuotePriceLabel = item => `$${formatQuotePrice(item)} ex GST`;
  const getQuoteName = item => {
    const provider = item?.providerDisplayName || item?.provider_name || item?.provider || '';
    const name = item?.name || item?.service_name || item?.service || 'Courier service';
    return provider ? `${provider}: ${name}` : name;
  };
  const openHsLookup = async description => {
    const query = encodeURIComponent(String(description || 'goods').trim() || 'goods');
    const urls = [
      `https://www.google.com/search?q=${query}+HS+tariff+code+site%3Atariff-finder.govt.nz`,
      'https://www.tariff-finder.govt.nz/',
    ];
    try {
      await Linking.openURL(urls[0]);
    } catch (_e) {
      await Linking.openURL(urls[1]);
    }
  };
  const confirmPackOnly = () => {
    Alert.alert(
      'Pack without label?',
      'This will mark the order packed without creating or printing a shipping label.',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Pack Only',
          style: 'destructive',
          onPress: () => handleFinalPackAndPrint(null, null, forceOverrideRef.current, null),
        },
      ]
    );
  };

  return (
    <Modal visible={labelModalVisible} transparent animationType="slide" statusBarTranslucent>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={Platform.OS === 'android' ? 20 : 0}
        style={{ flex: 1 }}
      >
        <View
            style={{
              flex: 1,
              backgroundColor: 'rgba(0,0,0,0.72)',
              justifyContent: 'center',
              paddingTop: Platform.OS === 'android' ? 42 : 28,
              paddingBottom: Platform.OS === 'android' ? 28 : 18,
            }}
        >
            <View
              style={[
                styles.modalContentAlt,
                {
                  maxHeight: '92%',
                  width: '100%',
                  padding: 0,
                  paddingBottom: 0,
                  borderBottomLeftRadius: 25,
                  borderBottomRightRadius: 25,
                  overflow: 'hidden',
                },
              ]}
            >
              <ScrollView
                nestedScrollEnabled
                keyboardShouldPersistTaps="handled"
                showsVerticalScrollIndicator={true}
                persistentScrollbar
                style={{ maxHeight: '100%' }}
                contentContainerStyle={{ padding: 20, paddingBottom: 30 }}
              >
                <View>
                <Text style={{ fontSize: 19, fontWeight: 'bold', marginBottom: 5, textAlign: 'center' }}>
                  Print Shipping Label
                </Text>

                <View
                  style={{
                    marginBottom: 8,
                    padding: 9,
                    borderRadius: 8,
                    backgroundColor: '#f4f7fa',
                    borderWidth: 1,
                    borderColor: '#e2e8ee',
                  }}
                >
                  <Text style={{ fontSize: 14, fontWeight: '800', color: '#1f2933', marginBottom: 2 }}>
                    {String(selectedOrder?.name || '')}
                  </Text>
                  {!!orderAddress && (
                    <Text style={{ fontSize: 12, color: '#485a6a' }} numberOfLines={2}>
                      {orderAddress}
                    </Text>
                  )}
                </View>

                {isInternational && (
                  <View
                    style={{
                      marginBottom: 8,
                      padding: 9,
                      borderRadius: 8,
                      backgroundColor: '#fef3c7',
                      borderWidth: 1,
                      borderColor: '#fbbf24',
                    }}
                  >
                    <Text style={{ color: '#92400e', fontWeight: '900', fontSize: 13 }}>
                      International order
                    </Text>
                    <Text style={{ color: '#92400e', fontSize: 12, marginTop: 2 }}>
                      Use Live Pricing or Custom Box only. Print with a non-thermal printer.
                    </Text>
                  </View>
                )}

                <View
                  style={{
                    flexDirection: 'row',
                    marginBottom: 10,
                    backgroundColor: '#eee',
                    borderRadius: 8,
                    padding: 3,
                  }}
                >
                  {[
                    ['quick', 'Quick Print'],
                    ['live', 'Live Pricing'],
                    ['custom', 'Custom Box'],
                  ].filter(([mode]) => (!isInternational || mode !== 'quick') && (mode !== 'quick' || hasQuickPrintStocks)).map(([mode, label]) => {
                    const active = labelMode === mode;
                    return (
                      <TouchableOpacity
                        key={mode}
                        style={[styles.tabBtn, active && styles.tabBtnActive]}
                        onPress={() => {
                          setLabelMode(mode);
                          setSatchelQuotes([]);
                          setSatchelQuoteErrors([]);
                          setSatchelQuoteProviders([]);
                        }}
                      >
                        <Text style={[styles.tabText, active && styles.tabTextActive]}>{label}</Text>
                      </TouchableOpacity>
                    );
                  })}
                </View>

                {isInternational && (
                  <View style={{ marginBottom: 10 }}>
                    <View style={{ borderRadius: 8, backgroundColor: '#f8fafc', borderWidth: 1, borderColor: '#dbe3ea', marginBottom: 8, overflow: 'hidden' }}>
                      <TouchableOpacity
                        style={{ padding: 11, backgroundColor: '#e5e7eb', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}
                        onPress={() => setCustomsSectionOpen(prev => !prev)}
                      >
                        <View style={{ flex: 1, paddingRight: 8 }}>
                          <Text style={{ fontSize: 14, fontWeight: '900', color: '#1f2937' }}>International Consignment Details</Text>
                          {!customsSectionOpen && (
                            <Text style={{ color: '#64748b', fontSize: 11, marginTop: 2 }} numberOfLines={1}>
                              {selectedDescriptionLabel} | {internationalDetails?.currency || 'NZD'} | Ref {internationalDetails?.reference || orderNumber}
                            </Text>
                          )}
                        </View>
                        <Text style={{ color: '#475569', fontWeight: '900', fontSize: 18 }}>{customsSectionOpen ? '^' : 'v'}</Text>
                      </TouchableOpacity>

                      {customsSectionOpen && (
                        <View style={{ padding: 11 }}>
                          <Text style={{ color: '#334155', fontSize: 12, lineHeight: 17, marginBottom: 10 }}>
                            These fields tell customs why the parcel is leaving NZ. The defaults are usually fine for normal Shopify sales.
                          </Text>

                          <Text style={styles.dimLabel}>Detailed Description *</Text>
                          <TouchableOpacity
                            style={[styles.dimInput, { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: descriptionDropdownOpen ? 0 : 8 }]}
                            onPress={() => setDescriptionDropdownOpen(prev => !prev)}
                          >
                            <Text style={{ fontSize: 15, fontWeight: '800', color: '#111827' }}>{selectedDescriptionLabel}</Text>
                            <Text style={{ fontSize: 16, fontWeight: '900', color: '#475569' }}>{descriptionDropdownOpen ? '^' : 'v'}</Text>
                          </TouchableOpacity>
                          {descriptionDropdownOpen && (
                            <View style={{ borderWidth: 1, borderColor: '#d1d5db', borderRadius: 8, marginBottom: 8, backgroundColor: '#fff', overflow: 'hidden' }}>
                              {descriptionOptions.map(([value, label]) => (
                                <TouchableOpacity
                                  key={value}
                                  style={{ paddingVertical: 11, paddingHorizontal: 12, backgroundColor: internationalDetails?.detailedDescription === value ? '#e8f4fd' : '#fff', borderBottomWidth: 1, borderBottomColor: '#eef2f7' }}
                                  onPress={() => {
                                    updateInternationalDetails({ detailedDescription: value, detailedDescriptionLabel: label });
                                    setDescriptionDropdownOpen(false);
                                  }}
                                >
                                  <Text style={{ color: internationalDetails?.detailedDescription === value ? '#007ace' : '#1f2937', fontWeight: '700' }}>{label}</Text>
                                </TouchableOpacity>
                              ))}
                            </View>
                          )}

                          {internationalDetails?.detailedDescription === '5' && (
                            <View style={{ marginBottom: 8 }}>
                              <Text style={styles.dimLabel}>If Other, Please Specify *</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left' }]}
                                placeholder="Describe the shipment reason"
                                value={internationalDetails?.otherDescription || ''}
                                maxLength={50}
                                onChangeText={t => updateInternationalDetails({ otherDescription: t })}
                              />
                            </View>
                          )}

                          <View style={{ flexDirection: 'row', gap: 8, marginBottom: 8 }}>
                            <View style={{ flex: 1 }}>
                              <Text style={styles.dimLabel}>Receiver Tax No.</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left' }]}
                                placeholder="Optional"
                                value={internationalDetails?.receiverTaxNo || ''}
                                maxLength={50}
                                onChangeText={t => updateInternationalDetails({ receiverTaxNo: t })}
                              />
                            </View>
                            <View style={{ flex: 1 }}>
                              <Text style={styles.dimLabel}>Currency</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left' }]}
                                placeholder="NZD"
                                value={internationalDetails?.currency || 'NZD'}
                                maxLength={3}
                                autoCapitalize="characters"
                                onChangeText={t => updateInternationalDetails({ currency: t.toUpperCase() })}
                              />
                            </View>
                          </View>

                          <View style={{ marginBottom: 8 }}>
                            <Text style={styles.dimLabel}>Receiver Email *</Text>
                            <TextInput
                              style={[styles.dimInput, { textAlign: 'left' }]}
                              placeholder="customer@example.com"
                              value={internationalDetails?.receiverEmail || ''}
                              autoCapitalize="none"
                              keyboardType="email-address"
                              onChangeText={t => updateInternationalDetails({ receiverEmail: t })}
                            />
                          </View>

                          <View style={{ flexDirection: 'row', gap: 8 }}>
                            <View style={{ flex: 1 }}>
                              <Text style={styles.dimLabel}>Reference</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left' }]}
                                placeholder="Order number"
                                value={internationalDetails?.reference || orderNumber}
                                maxLength={50}
                                onChangeText={t => updateInternationalDetails({ reference: t })}
                              />
                            </View>
                            <View style={{ flex: 1 }}>
                              <Text style={styles.dimLabel}>Date *</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left' }]}
                                placeholder="YYYY-MM-DD"
                                value={internationalDetails?.date || todayIso()}
                                onChangeText={t => updateInternationalDetails({ date: t })}
                              />
                            </View>
                          </View>
                        </View>
                      )}
                    </View>

                    <View style={{ borderRadius: 8, backgroundColor: '#f8fafc', borderWidth: 1, borderColor: '#dbe3ea', marginBottom: 8, overflow: 'hidden' }}>
                      <TouchableOpacity
                        style={{ padding: 11, backgroundColor: '#e5e7eb', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}
                        onPress={() => setInvoiceSectionOpen(prev => !prev)}
                      >
                        <View style={{ flex: 1, paddingRight: 8 }}>
                          <Text style={{ fontSize: 14, fontWeight: '900', color: '#1f2937' }}>Invoice Declaration</Text>
                          {!invoiceSectionOpen && (
                            <Text style={{ color: '#64748b', fontSize: 11, marginTop: 2 }}>
                              {(internationalDetails?.items || []).length || 0} line item(s)
                            </Text>
                          )}
                        </View>
                        <Text style={{ color: '#475569', fontWeight: '900', fontSize: 18 }}>{invoiceSectionOpen ? '^' : 'v'}</Text>
                      </TouchableOpacity>

                      {invoiceSectionOpen && (
                        <View style={{ padding: 11 }}>
                          <Text style={{ color: '#334155', fontSize: 12, lineHeight: 17, marginBottom: 10 }}>
                            This is what prints on the customs invoice. Check description, quantity, net weight, declared value, origin, and HS tariff if known.
                          </Text>
                          {(internationalDetails?.items || []).map((item, index) => (
                            <View key={`intl-item-${index}`} style={{ padding: 9, borderRadius: 7, backgroundColor: '#fff', borderWidth: 1, borderColor: '#e5e7eb', marginBottom: 8 }}>
                              <Text style={{ color: '#475569', fontWeight: '900', fontSize: 12, marginBottom: 6 }}>
                                Item {index + 1}
                              </Text>
                              <Text style={styles.dimLabel}>Description *</Text>
                              <TextInput
                                style={[styles.dimInput, { textAlign: 'left', marginBottom: 7 }]}
                                placeholder="Goods Description"
                                value={item.description}
                                maxLength={50}
                                onChangeText={t => updateInternationalItem(index, { description: t })}
                              />
                              <View style={{ flexDirection: 'row', gap: 6, marginBottom: 7 }}>
                                <View style={{ flex: 1 }}>
                                  <Text style={styles.dimLabel}>Qty *</Text>
                                  <TextInput
                                    style={styles.dimInput}
                                    keyboardType="numeric"
                                    value={String(item.quantity || '')}
                                    onChangeText={t => updateInternationalItem(index, { quantity: t })}
                                  />
                                </View>
                                <View style={{ flex: 1 }}>
                                  <Text style={styles.dimLabel}>Net Wgt. Kg *</Text>
                                  <TextInput
                                    style={styles.dimInput}
                                    keyboardType="numeric"
                                    value={String(item.netWeight || '')}
                                    onChangeText={t => updateInternationalItem(index, { netWeight: t })}
                                  />
                                </View>
                                <View style={{ flex: 1 }}>
                                  <Text style={styles.dimLabel}>Value $ *</Text>
                                  <TextInput
                                    style={styles.dimInput}
                                    keyboardType="numeric"
                                    value={String(item.value || '')}
                                    onChangeText={t => updateInternationalItem(index, { value: t })}
                                  />
                                </View>
                              </View>
                              <View style={{ flexDirection: 'row', gap: 6 }}>
                                <View style={{ flex: 1 }}>
                                  <Text style={styles.dimLabel}>Origin *</Text>
                                  <TouchableOpacity
                                    style={[styles.dimInput, { minHeight: 44, justifyContent: 'center' }]}
                                    onPress={() => {
                                      setOriginDropdownIndex(originDropdownIndex === index ? null : index);
                                      setOriginSearch('');
                                    }}
                                  >
                                    <Text style={{ fontWeight: '800', color: '#111827', textAlign: 'center' }} numberOfLines={1} adjustsFontSizeToFit>
                                      {getCountryName(item.countryOfOrigin)}
                                    </Text>
                                  </TouchableOpacity>
                                </View>
                                <View style={{ flex: 2 }}>
                                  <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <Text style={styles.dimLabel}>HS Tariff No. *</Text>
                                    <TouchableOpacity
                                      style={{ paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6, backgroundColor: '#e8f4fd', marginBottom: 4 }}
                                      onPress={() => openHsLookup(item.description)}
                                    >
                                      <Text style={{ color: '#007ace', fontWeight: '900', fontSize: 11 }}>LOOKUP</Text>
                                    </TouchableOpacity>
                                  </View>
                                  <TextInput
                                    style={[styles.dimInput, { textAlign: 'left' }]}
                                    placeholder="e.g. 33059000"
                                    value={String(item.hsTariff || '')}
                                    keyboardType="numeric"
                                    maxLength={10}
                                    onChangeText={t => updateInternationalItem(index, { hsTariff: t.replace(/\D/g, '') })}
                                  />
                                </View>
                              </View>
                              {originDropdownIndex === index && (
                                <View style={{ marginTop: 8, borderWidth: 1, borderColor: '#d1d5db', borderRadius: 8, backgroundColor: '#fff', overflow: 'hidden' }}>
                                  <TextInput
                                    style={[styles.dimInput, { textAlign: 'left', borderWidth: 0, borderBottomWidth: 1, borderRadius: 0 }]}
                                    placeholder="Search country"
                                    value={originSearch}
                                    onChangeText={setOriginSearch}
                                    autoCorrect={false}
                                  />
                                  <ScrollView nestedScrollEnabled keyboardShouldPersistTaps="handled" style={{ maxHeight: 190 }}>
                                    {filteredCountryOptions.map(([code, name]) => (
                                      <TouchableOpacity
                                        key={code}
                                        style={{
                                          paddingVertical: 11,
                                          paddingHorizontal: 12,
                                          backgroundColor: String(item.countryOfOrigin || '').toUpperCase() === code ? '#e8f4fd' : '#fff',
                                          borderBottomWidth: 1,
                                          borderBottomColor: '#eef2f7',
                                        }}
                                        onPress={() => {
                                          updateInternationalItem(index, { countryOfOrigin: code });
                                          setOriginDropdownIndex(null);
                                          setOriginSearch('');
                                        }}
                                      >
                                        <Text style={{ color: String(item.countryOfOrigin || '').toUpperCase() === code ? '#007ace' : '#1f2937', fontWeight: '700' }}>
                                          {name}
                                        </Text>
                                      </TouchableOpacity>
                                    ))}
                                  </ScrollView>
                                </View>
                              )}
                            </View>
                          ))}
                        </View>
                      )}
                    </View>
                  </View>
                )}

                {labelMode !== 'custom' ? (
                  <>
                    {labelMode === 'live' && (
                      <View
                        style={{
                          marginBottom: 8,
                          padding: 8,
                          borderRadius: 7,
                          backgroundColor: '#f4f7fa',
                          borderWidth: 1,
                          borderColor: '#e2e8ee',
                        }}
                      >
                        <Text style={{ color: '#334', fontWeight: '700', fontSize: 13 }}>
                          Live pricing
                        </Text>
                        <Text style={{ color: '#667', fontSize: 12, marginTop: 2 }}>
                          Quotes will be pulled from all Packie carrier options for the selected stock.
                        </Text>
                      </View>
                    )}

                    {activeStockList.length === 0 ? (
                      <View style={{ marginBottom: 10, padding: 12, borderRadius: 8, backgroundColor: '#fff7ed', borderWidth: 1, borderColor: '#fed7aa' }}>
                        <Text style={{ color: '#9a3412', fontWeight: '800', fontSize: 13 }}>
                          {labelMode === 'quick' ? 'No quick print stocks enabled.' : 'No live pricing stocks available.'}
                        </Text>
                      </View>
                    ) : (
                      <ScrollView
                        showsVerticalScrollIndicator={false}
                        keyboardShouldPersistTaps="handled"
                        contentContainerStyle={{ paddingBottom: 6 }}
                        style={{ maxHeight: labelMode === 'live' ? 240 : 360, marginBottom: 10 }}
                      >
                        {activeStockList.map(item => {
                          const active = String(selectedStockId) === String(item.id);
                          const label = String(item.display_name || item.display_label || item.name || item.label || item.code || item.package_code || '').replace(/^SATCHEL\s+/i, 'Satchel ');
                          return (
                            <TouchableOpacity
                              key={item.id.toString()}
                              style={[
                                {
                                  width: '100%',
                                  paddingHorizontal: 14,
                                  paddingVertical: 18,
                                  borderRadius: 8,
                                  backgroundColor: active ? '#e8f4fd' : '#f3f4f6',
                                  borderWidth: active ? 2 : 1,
                                  borderColor: active ? '#007ace' : '#e5e7eb',
                                  alignItems: 'center',
                                  marginBottom: 10,
                                },
                              ]}
                              onPress={() => {
                                setSelectedStockId(item.id);
                                setSatchelQuotes([]);
                                setSatchelQuoteErrors([]);
                                setSatchelQuoteProviders([]);
                              }}
                            >
                              <Text
                                style={{ fontSize: 19, fontWeight: active ? '900' : '800', color: active ? '#007ace' : '#374151' }}
                              >
                                {label || item.name || item.label}
                              </Text>
                              {labelMode === 'quick' && item.carrier ? (
                                <Text style={{ color: '#667', fontSize: 12, fontWeight: '700', marginTop: 3 }}>
                                  {item.carrier}
                                </Text>
                              ) : null}
                            </TouchableOpacity>
                          );
                        })}
                      </ScrollView>
                    )}

                    {labelMode === 'quick' ? (
                      <View style={{ marginBottom: 10 }}>
                        <TouchableOpacity
                          style={[styles.packBtn, { backgroundColor: activeStockList.length === 0 ? '#9ca3af' : themeColor, paddingVertical: 20, marginBottom: 10 }]}
                          onPress={() => submitPrintAndPack(selectedStockId, null)}
                          disabled={activeStockList.length === 0}
                        >
                          <Text style={{ color: '#fff', fontWeight: '900', fontSize: 18 }}>PRINT & PACK</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                          style={[styles.packBtn, { backgroundColor: '#e67e22', paddingVertical: 15 }]}
                          onPress={confirmPackOnly}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>PACK ONLY</Text>
                        </TouchableOpacity>
                      </View>
                    ) : (
                      <>
                        {satchelQuotes.length === 0 ? (
                          <TouchableOpacity
                            style={[
                              styles.packBtn,
                              { marginBottom: 10, backgroundColor: isFetchingSatchelQuotes || activeStockList.length === 0 ? '#ccc' : '#007ace' },
                            ]}
                            onPress={() => {
                              const details = requireInternationalDetails();
                              if (isInternational && !details) return;
                              handleGetSatchelQuotes(details);
                            }}
                            disabled={isFetchingSatchelQuotes || activeStockList.length === 0}
                          >
                            <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                              {isFetchingSatchelQuotes ? 'CALCULATING...' : 'GET LIVE PRICING'}
                            </Text>
                          </TouchableOpacity>
                        ) : (
                          <FlatList
                            data={satchelQuotes}
                            keyExtractor={(item, index) => `${item?.provider || 'provider'}-${item?.id || index}`}
                            style={{ maxHeight: 290, marginBottom: 8 }}
                            nestedScrollEnabled
                            keyboardShouldPersistTaps="handled"
                            renderItem={({ item }) => {
                              const extras = getQuoteExtras(item);
                              return (
                                <TouchableOpacity
                                  style={[
                                    {
                                      flexDirection: 'row',
                                      justifyContent: 'space-between',
                                      alignItems: 'center',
                                      paddingHorizontal: 12,
                                      paddingVertical: 15,
                                      borderRadius: 8,
                                      backgroundColor: '#f9f9f9',
                                      marginBottom: 7,
                                      borderWidth: 1,
                                      borderColor: '#edf0f2',
                                    },
                                  ]}
                                  onPress={() =>
                                    submitPrintAndPack(selectedStockId, item)
                                  }
                                >
                                  <View style={{ flex: 1, marginRight: 10 }}>
                                    <Text style={{ fontSize: 16, fontWeight: 'bold', color: '#444' }}>
                                      {getQuoteName(item)}
                                    </Text>
                                    {extras.length > 0 && (
                                      <Text style={{ fontSize: 12, color: '#667', marginTop: 2 }}>
                                        {extras.map(([label, amount]) => `${label} +$${amount.toFixed(2)}`).join(' | ')}
                                      </Text>
                                    )}
                                  </View>
                                  <Text
                                    style={{ fontSize: 15, fontWeight: '900', color: themeColor, minWidth: 92, textAlign: 'right' }}
                                    numberOfLines={1}
                                    adjustsFontSizeToFit
                                  >
                                    {formatQuotePriceLabel(item)}
                                  </Text>
                                </TouchableOpacity>
                              );
                            }}
                          />
                        )}
                        {satchelQuoteErrors?.length > 0 && (
                          <View style={{ marginBottom: 10, padding: 9, borderRadius: 8, backgroundColor: '#fff7ed', borderWidth: 1, borderColor: '#fed7aa' }}>
                            {satchelQuoteProviders?.length > 0 && (
                              <Text style={{ color: '#9a3412', fontSize: 12, fontWeight: '800', marginBottom: 3 }}>
                                Checked: {satchelQuoteProviders.join(', ')}
                              </Text>
                            )}
                            {satchelQuoteErrors.map((msg, idx) => (
                              <Text key={`satchel-quote-error-${idx}`} style={{ color: '#9a3412', fontSize: 12 }}>
                                {msg}
                              </Text>
                            ))}
                          </View>
                        )}

                        <TouchableOpacity
                          style={[styles.packBtn, { backgroundColor: '#e67e22', marginBottom: 8, paddingVertical: 15 }]}
                          onPress={confirmPackOnly}
                        >
                          <Text style={{ color: '#fff', fontWeight: 'bold' }}>PACK ONLY</Text>
                        </TouchableOpacity>
                      </>
                    )}
                  </>
                ) : (
                  <View>
                    <View
                      style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        gap: 10,
                        marginBottom: 15,
                      }}
                    >
                      <View style={{ flex: 1 }}>
                        <Text style={styles.dimLabel}>Weight (kg)</Text>
                        <TextInput
                          style={styles.dimInput}
                          keyboardType="numeric"
                          placeholder="0.5"
                          returnKeyType="next"
                          value={customDims.weight}
                          onChangeText={t => setCustomDims({ ...customDims, weight: t })}
                        />
                      </View>
                      <View style={{ flex: 1 }}>
                        <Text style={styles.dimLabel}>L (cm)</Text>
                        <TextInput
                          style={styles.dimInput}
                          keyboardType="numeric"
                          placeholder="30"
                          returnKeyType="next"
                          value={customDims.l}
                          onChangeText={t => setCustomDims({ ...customDims, l: t })}
                        />
                      </View>
                      <View style={{ flex: 1 }}>
                        <Text style={styles.dimLabel}>W (cm)</Text>
                        <TextInput
                          style={styles.dimInput}
                          keyboardType="numeric"
                          placeholder="20"
                          returnKeyType="next"
                          value={customDims.w}
                          onChangeText={t => setCustomDims({ ...customDims, w: t })}
                        />
                      </View>
                      <View style={{ flex: 1 }}>
                        <Text style={styles.dimLabel}>H (cm)</Text>
                        <TextInput
                          style={styles.dimInput}
                          keyboardType="numeric"
                          placeholder="10"
                          returnKeyType="done"
                          value={customDims.h}
                          onChangeText={t => setCustomDims({ ...customDims, h: t })}
                        />
                      </View>
                    </View>

                    {customQuotes.length === 0 ? (
                      <TouchableOpacity
                        style={[
                          styles.packBtn,
                          { marginBottom: 10, backgroundColor: isFetchingQuotes ? '#ccc' : '#007ace' },
                        ]}
                        onPress={() => {
                          const details = requireInternationalDetails();
                          if (isInternational && !details) return;
                          handleGetQuotes(details);
                        }}
                        disabled={isFetchingQuotes}
                      >
                        <Text style={{ color: '#fff', fontWeight: 'bold' }}>
                          {isFetchingQuotes ? 'CALCULATING...' : 'GET LIVE QUOTES'}
                        </Text>
                      </TouchableOpacity>
                    ) : (
                      <FlatList
                        data={customQuotes}
                        keyExtractor={(item, index) => index.toString()}
                        style={{ maxHeight: 180, marginBottom: 10 }}
                        nestedScrollEnabled
                        keyboardShouldPersistTaps="handled"
                        renderItem={({ item }) => {
                          return (
                            <TouchableOpacity
                              style={[
                                styles.stockRowBtn,
                                { flexDirection: 'row', justifyContent: 'space-between' },
                              ]}
                              onPress={() =>
                                submitPrintAndPack('custom', item)
                              }
                            >
                              <Text style={{ fontSize: 14, fontWeight: 'bold', color: '#444' }}>
                                {getQuoteName(item)}
                              </Text>
                              <Text
                                style={{ fontSize: 14, fontWeight: '900', color: themeColor, minWidth: 92, textAlign: 'right' }}
                                numberOfLines={1}
                                adjustsFontSizeToFit
                              >
                                {formatQuotePriceLabel(item)}
                              </Text>
                            </TouchableOpacity>
                          );
                        }}
                      />
                    )}
                    <TouchableOpacity
                      style={[styles.packBtn, { backgroundColor: '#e67e22', marginBottom: 8, paddingVertical: 15 }]}
                      onPress={confirmPackOnly}
                    >
                      <Text style={{ color: '#fff', fontWeight: 'bold' }}>PACK ONLY</Text>
                    </TouchableOpacity>
                  </View>
                )}

                <TouchableOpacity
                  style={[styles.packBtn, { backgroundColor: '#7f8c8d', paddingVertical: 12 }]}
                  onPress={() => {
                    setLabelModalVisible(false);
                    setCustomQuotes([]);
                    setSatchelQuotes([]);
                    setSatchelQuoteErrors([]);
                    setSatchelQuoteProviders([]);
                    setLabelMode(initialLabelMode);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold' }}>CANCEL</Text>
                </TouchableOpacity>
                </View>
              </ScrollView>
            </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
