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

export function AddressModal() {
  const [showContactFields, setShowContactFields] = useState(false);
  const {
    addressModalVisible,
    setAddressModalVisible,
    selectedOrder,
    addressSearch,
    setAddressSearch,
    addressResults,
    isSearchingAddress,
    parsedAddress,
    setParsedAddress,
    handleSearchAddress,
    handleSelectAddress,
    handleSaveAddress,
    themeColor,
  } = useApp();

  return (
    <Modal visible={addressModalVisible} transparent animationType="fade">
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
        <View style={styles.modalOverlayTop}>
          <View style={[styles.modalContentTop, { minHeight: 450 }]}>
            <Text style={{ fontSize: 20, fontWeight: 'bold', marginBottom: 15 }}>Fix Shipping Address</Text>

            <View style={{ backgroundColor: '#fff5ea', borderColor: '#eecd9d', borderWidth: 1, padding: 12, borderRadius: 8, marginBottom: 15 }}>
              <Text style={{ fontSize: 12, color: '#8a6116', fontWeight: 'bold', marginBottom: 4 }}>ORIGINAL CUSTOMER ENTRY:</Text>
              <Text style={{ fontSize: 15, color: '#333' }}>{selectedOrder?.original_address || selectedOrder?.address}</Text>
              {selectedOrder?.postcode && !selectedOrder?.original_address ? (
                <Text style={{ fontSize: 15, color: '#333' }}>{selectedOrder?.postcode}</Text>
              ) : null}
            </View>

            {selectedOrder?.corrected_address ? (
              <View style={{ backgroundColor: '#eafaf1', borderColor: '#a9dfbf', borderWidth: 1, padding: 12, borderRadius: 8, marginBottom: 15 }}>
                <Text style={{ fontSize: 12, color: '#1e8449', fontWeight: 'bold', marginBottom: 4 }}>CORRECTED ADDRESS:</Text>
                <Text style={{ fontSize: 15, color: '#333' }}>{selectedOrder.corrected_address}</Text>
              </View>
            ) : null}

            {!parsedAddress ? (
              <ScrollView
                keyboardShouldPersistTaps="handled"
                showsVerticalScrollIndicator={true}
                persistentScrollbar={true}
                contentContainerStyle={{ paddingBottom: 10 }}
              >
                <Text style={{ color: '#666', marginBottom: 10, fontWeight: 'bold' }}>Address Search:</Text>
                <View style={{ flexDirection: 'row', gap: 10, marginBottom: 10 }}>
                  <TextInput
                    style={[styles.dimInput, { flex: 1, textAlign: 'left' }]}
                    placeholder="e.g. 26 Bridge Ave"
                    value={addressSearch}
                    onChangeText={setAddressSearch}
                    onSubmitEditing={handleSearchAddress}
                  />
                  <TouchableOpacity
                    style={[styles.packBtn, { paddingHorizontal: 15, backgroundColor: '#007ace' }]}
                    onPress={handleSearchAddress}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>{isSearchingAddress ? '...' : 'SEARCH'}</Text>
                  </TouchableOpacity>
                </View>

                <FlatList
                  data={addressResults}
                  keyExtractor={item => item.address_id || item.id || item.full_address || String(Math.random())}
                  keyboardShouldPersistTaps="handled"
                  style={{ maxHeight: 220 }}
                  renderItem={({ item }) => (
                    <TouchableOpacity style={styles.stockRowBtn} onPress={() => handleSelectAddress(item)}>
                      <Text style={{ fontSize: 14 }}>{item.full_address || item.address || item.label || JSON.stringify(item)}</Text>
                    </TouchableOpacity>
                  )}
                />

                {addressSearch.length > 0 && addressResults.length === 0 && !isSearchingAddress && (
                  <TouchableOpacity
                    style={[styles.packBtn, { backgroundColor: '#e67e22', marginTop: 15 }]}
                    onPress={() => handleSelectAddress(addressSearch)}
                  >
                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>ENTER MANUALLY</Text>
                  </TouchableOpacity>
                )}

                <TouchableOpacity
                  style={[styles.packBtn, { backgroundColor: '#7f8c8d', marginTop: 10 }]}
                  onPress={() => {
                    setAddressModalVisible(false);
                    setParsedAddress(null);
                    setShowContactFields(false);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold' }}>CANCEL</Text>
                </TouchableOpacity>
              </ScrollView>
            ) : (
              <ScrollView
                keyboardShouldPersistTaps="handled"
                showsVerticalScrollIndicator={true}
                persistentScrollbar={true}
                contentContainerStyle={{ paddingBottom: 10 }}
              >
                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 12 }}>
                  <Text style={{ fontWeight: 'bold', color: themeColor, fontSize: 16 }}>Verify Details:</Text>
                  <TouchableOpacity
                    style={[styles.refreshBtn, { backgroundColor: '#eef2f3' }]}
                    onPress={() => setShowContactFields(prev => !prev)}
                  >
                    <Text style={{ color: '#333', fontWeight: 'bold', fontSize: 11 }}>
                      {showContactFields ? 'HIDE CONTACT' : 'PHONE / EMAIL'}
                    </Text>
                  </TouchableOpacity>
                </View>

                <Text style={styles.dimLabel}>Contact Name</Text>
                <TextInput
                  style={[styles.dimInput, { textAlign: 'left', marginBottom: 10 }]}
                  value={parsedAddress.contactName}
                  onChangeText={t => setParsedAddress({ ...parsedAddress, contactName: t })}
                />

                <View style={{ flexDirection: 'row', gap: 10, marginBottom: 10 }}>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.dimLabel}>Company</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      placeholder="Optional"
                      value={parsedAddress.company}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, company: t })}
                    />
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.dimLabel}>Building</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      placeholder="Optional"
                      value={parsedAddress.building}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, building: t })}
                    />
                  </View>
                </View>

                {showContactFields ? (
                  <View style={{ flexDirection: 'row', gap: 10, marginBottom: 10 }}>
                    <View style={{ flex: 1 }}>
                      <Text style={styles.dimLabel}>Phone</Text>
                      <TextInput
                        style={[styles.dimInput, { textAlign: 'left' }]}
                        keyboardType="phone-pad"
                        value={parsedAddress.phone}
                        onChangeText={t => setParsedAddress({ ...parsedAddress, phone: t })}
                      />
                    </View>
                    <View style={{ flex: 1 }}>
                      <Text style={styles.dimLabel}>Email</Text>
                      <TextInput
                        style={[styles.dimInput, { textAlign: 'left' }]}
                        keyboardType="email-address"
                        autoCapitalize="none"
                        value={parsedAddress.email}
                        onChangeText={t => setParsedAddress({ ...parsedAddress, email: t })}
                      />
                    </View>
                  </View>
                ) : null}

                <View style={{ flexDirection: 'row', gap: 10, marginBottom: 10 }}>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.dimLabel}>Unit / Flat</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      placeholder="e.g. Unit 2"
                      value={parsedAddress.unit}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, unit: t })}
                    />
                  </View>
                  <View style={{ flex: 2 }}>
                    <Text style={styles.dimLabel}>Street</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      value={parsedAddress.address1}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, address1: t })}
                    />
                  </View>
                </View>

                <Text style={styles.dimLabel}>Suburb</Text>
                <TextInput
                  style={[styles.dimInput, { textAlign: 'left', marginBottom: 10 }]}
                  value={parsedAddress.address2}
                  onChangeText={t => setParsedAddress({ ...parsedAddress, address2: t })}
                />

                <View style={{ flexDirection: 'row', gap: 10, marginBottom: 10 }}>
                  <View style={{ flex: 2 }}>
                    <Text style={styles.dimLabel}>City</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      value={parsedAddress.city}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, city: t })}
                    />
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.dimLabel}>Postcode</Text>
                    <TextInput
                      style={[styles.dimInput, { textAlign: 'left' }]}
                      keyboardType="numeric"
                      value={parsedAddress.zip}
                      onChangeText={t => setParsedAddress({ ...parsedAddress, zip: t })}
                    />
                  </View>
                </View>

                <Text style={styles.dimLabel}>Delivery Notes (Gate codes, etc.)</Text>
                <TextInput
                  style={[styles.dimInput, { textAlign: 'left', marginBottom: 20 }]}
                  placeholder="Leave at back door..."
                  value={parsedAddress.notes}
                  onChangeText={t => setParsedAddress({ ...parsedAddress, notes: t })}
                />

                <TouchableOpacity
                  style={[styles.packBtn, { backgroundColor: themeColor, marginBottom: 10 }]}
                  onPress={() => {
                    setShowContactFields(false);
                    handleSaveAddress();
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 16 }}>UPDATE ADDRESS</Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={[styles.packBtn, { backgroundColor: '#7f8c8d' }]}
                  onPress={() => {
                    setAddressModalVisible(false);
                    setParsedAddress(null);
                    setShowContactFields(false);
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold' }}>CANCEL</Text>
                </TouchableOpacity>
              </ScrollView>
            )}
            {parsedAddress ? (
              <Text style={{ color: '#777', textAlign: 'center', fontSize: 11, fontWeight: 'bold', marginTop: 6 }}>
                Swipe for actions below
              </Text>
            ) : null}
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
