import React, { useEffect, useReducer, useCallback, useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Modal,
  FlatList,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import {
  lookupLocation,
  reverseGeocode,
  validatePincode,
  pincodeHasDeliveryOffice,
  type AddressComponents,
} from '../core/api';
import { checkServiceability, type ServiceabilityResult } from '../core/checkout-api';
import { processLocalityLookup } from '../core/locality';
import type {
  AddressFormProps,
  AddressLabel,
  AdministrativeInfo,
  CompleteAddress,
  LocationAlternative,
} from '../core/types';
import { styles, COLORS } from '../styles/checkout.native';
import { AddressDetailsIcon, AddressLabelIcon } from './AddressLabelIcons.native';

// ─── State (identical logic to web AddressForm) ───────────────────────────────

interface ManualFields {
  flatNumber: string;
  floorNumber: string;
  buildingName: string;
  streetName: string;
}

type FormState =
  | { status: 'loading' }
  | { status: 'error'; message: string }
  | {
      status: 'ready';
      adminInfo: AdministrativeInfo;
      alternatives: LocationAlternative[];
      localityOptions: string[];
      selectedLocality: string;
      selectedLabel: AddressLabel;
      labelText: string;
      fields: ManualFields;
      submitting: boolean;
      pincodeHasDelivery: boolean;
      serviceabilityResult: ServiceabilityResult | null;
    };

type FormAction =
  | { type: 'LOAD_START' }
  | {
      type: 'LOAD_SUCCESS';
      adminInfo: AdministrativeInfo;
      alternatives: LocationAlternative[];
      addressComponents: AddressComponents;
      pincodeHasDelivery: boolean;
      serviceabilityResult: ServiceabilityResult | null;
    }
  | { type: 'LOAD_ERROR'; message: string }
  | { type: 'SET_FIELD'; key: keyof ManualFields; value: string }
  | { type: 'SET_LOCALITY'; locality: string }
  | { type: 'SET_LABEL'; label: AddressLabel }
  | { type: 'SET_LABEL_TEXT'; value: string }
  | { type: 'SUBMIT_START' }
  | { type: 'SUBMIT_END' };

const INITIAL_FIELDS: ManualFields = {
  flatNumber: '',
  floorNumber: '',
  buildingName: '',
  streetName: '',
};

function parseAddressComponents(components: AddressComponents): Partial<ManualFields> {
  const fields: Partial<ManualFields> = {};

  if (components.name) {
    fields.buildingName = components.name;
  } else if (components.building_name) {
    fields.buildingName = components.building_name;
  } else if (components.addr_housename) {
    fields.buildingName = components.addr_housename;
  }

  const streetParts: string[] = [];
  if (components.road) streetParts.push(components.road);
  if (components.suburb) streetParts.push(components.suburb);
  if (streetParts.length > 0) {
    fields.streetName = streetParts.join(', ');
  }

  return fields;
}

function reducer(state: FormState, action: FormAction): FormState {
  switch (action.type) {
    case 'LOAD_START':
      return { status: 'loading' };
    case 'LOAD_SUCCESS': {
      const preFilled = parseAddressComponents(action.addressComponents);
      const processed = processLocalityLookup(action.adminInfo, action.alternatives || []);
      return {
        status: 'ready',
        adminInfo: processed.adminInfo,
        alternatives: processed.alternatives,
        localityOptions: processed.localityOptions,
        selectedLocality: processed.selectedLocality,
        selectedLabel: 'home',
        labelText: '',
        fields: { ...INITIAL_FIELDS, ...preFilled },
        submitting: false,
        pincodeHasDelivery: action.pincodeHasDelivery,
        serviceabilityResult: action.serviceabilityResult,
      };
    }
    case 'LOAD_ERROR':
      return { status: 'error', message: action.message };
    case 'SET_FIELD':
      if (state.status !== 'ready') return state;
      return { ...state, fields: { ...state.fields, [action.key]: action.value } };
    case 'SET_LOCALITY':
      if (state.status !== 'ready') return state;
      return { ...state, selectedLocality: action.locality };
    case 'SET_LABEL':
      if (state.status !== 'ready') return state;
      return {
        ...state,
        selectedLabel: action.label,
        labelText: action.label === 'other' ? state.labelText : '',
      };
    case 'SET_LABEL_TEXT':
      if (state.status !== 'ready') return state;
      return { ...state, labelText: action.value.slice(0, 64) };
    case 'SUBMIT_START':
      if (state.status !== 'ready') return state;
      return { ...state, submitting: true };
    case 'SUBMIT_END':
      if (state.status !== 'ready') return state;
      return { ...state, submitting: false };
    default:
      return state;
  }
}

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * Native (iOS/Android) address form — identical business logic to web AddressForm.tsx,
 * rewritten with React Native primitives (TextInput, ScrollView, Modal picker).
 * Metro resolves this file on native; AddressForm.tsx is used on web.
 */
const AddressForm: React.FC<AddressFormProps> = ({
  digipin,
  lat,
  lng,
  apiKey,
  apiBaseUrl,
  onAddressComplete,
  onBack,
  onError,
  theme = 'light',
  checkoutConfig,
  serviceabilitySessionToken,
  enableServiceabilityCheck = false,
  showIndiaPostDeliveryWarning = false,
  serviceabilityBlockCheckout,
  onServiceabilityResult,
}) => {
  const [state, dispatch] = useReducer(reducer, { status: 'loading' });
  const [showLocalityPicker, setShowLocalityPicker] = useState(false);
  const [focusedField, setFocusedField] = useState<keyof ManualFields | null>(null);

  const isDark = theme === 'dark';

  // ── Fetch administrative data ──────────────────────────────────────────────
  const fetchAdminInfo = useCallback(async () => {
    dispatch({ type: 'LOAD_START' });
    try {
      const [adminRes, reverseRes] = await Promise.all([
        lookupLocation(lat, lng, apiKey, apiBaseUrl),
        reverseGeocode(digipin, apiKey, apiBaseUrl),
      ]);

      const pincode =
        adminRes.data.administrative_info.pincode?.replace(/\D/g, '').slice(0, 6) ?? '';
      if (pincode.length !== 6) {
        dispatch({
          type: 'LOAD_ERROR',
          message:
            'Could not determine a valid 6-digit pincode for this location. Please adjust the map pin.',
        });
        onError?.(new Error('Missing or invalid pincode'));
        return;
      }

      const pinValidation = await validatePincode(pincode, apiKey, apiBaseUrl);

      if (!pinValidation.isValid) {
        dispatch({
          type: 'LOAD_ERROR',
          message:
            'This location resolves to a pincode that is not in the India Post database. Please move the map pin to a valid address.',
        });
        onError?.(new Error('Invalid pincode for location'));
        return;
      }

      const hasDelivery = pincodeHasDeliveryOffice(pinValidation.offices);
      let serviceabilityResult: ServiceabilityResult | null = null;

      if (
        enableServiceabilityCheck
        && checkoutConfig?.functionBaseUrl
        && checkoutConfig.merchantId
        && serviceabilitySessionToken
      ) {
        try {
          serviceabilityResult = await checkServiceability(
            checkoutConfig,
            serviceabilitySessionToken,
            pincode,
            { lat, lng }
          );
          onServiceabilityResult?.(serviceabilityResult);
        } catch {
          // Fail open if the platform serviceability check itself is unavailable.
        }
      }

      dispatch({
        type: 'LOAD_SUCCESS',
        adminInfo: adminRes.data.administrative_info,
        alternatives: adminRes.data.alternatives || [],
        addressComponents: reverseRes.data.addressComponents,
        pincodeHasDelivery: hasDelivery,
        serviceabilityResult,
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Failed to fetch address data.';
      dispatch({ type: 'LOAD_ERROR', message: msg });
      onError?.(err instanceof Error ? err : new Error(msg));
    }
  }, [
    digipin,
    lat,
    lng,
    apiKey,
    apiBaseUrl,
    onError,
    checkoutConfig,
    serviceabilitySessionToken,
    enableServiceabilityCheck,
    onServiceabilityResult,
  ]);

  useEffect(() => {
    void fetchAdminInfo();
  }, [fetchAdminInfo]);

  // ── Submit ────────────────────────────────────────────────────────────────
  const handleSubmit = useCallback(() => {
    if (state.status !== 'ready') return;
    if (!state.fields.flatNumber.trim()) return;
    if (state.selectedLabel === 'other' && !state.labelText.trim()) return;
    const serviceabilityBlocked =
      state.serviceabilityResult?.checked
      && state.serviceabilityResult.serviceable === false
      && (serviceabilityBlockCheckout ?? state.serviceabilityResult.block_checkout);
    if (serviceabilityBlocked) return;

    const { adminInfo, selectedLocality, selectedLabel, labelText, fields } = state;

    const parts: string[] = [
      fields.flatNumber,
      fields.floorNumber ? `Floor ${fields.floorNumber}` : '',
      fields.buildingName,
      fields.streetName,
      selectedLocality,
      adminInfo.district,
      adminInfo.state,
      adminInfo.pincode,
    ].filter(Boolean);

    const complete: CompleteAddress = {
      digipin,
      lat,
      lng,
      state: adminInfo.state,
      district: adminInfo.district,
      division: adminInfo.division,
      locality: selectedLocality,
      pincode: adminInfo.pincode,
      delivery: adminInfo.delivery,
      country: adminInfo.country ?? 'India',
      ...fields,
      formattedAddress: parts.join(', '),
      label: selectedLabel,
      ...(selectedLabel === 'other' ? { labelText: labelText.trim() } : {}),
    };

    dispatch({ type: 'SUBMIT_START' });
    try {
      onAddressComplete(complete);
    } finally {
      dispatch({ type: 'SUBMIT_END' });
    }
  }, [state, digipin, lat, lng, onAddressComplete, serviceabilityBlockCheckout]);

  // ─── Field input helper ────────────────────────────────────────────────────
  const renderField = (
    key: keyof ManualFields,
    label: string,
    placeholder: string,
    required = false
  ) => (
    <View style={state.status === 'ready' ? undefined : { opacity: 0 }}>
      <View style={styles.fieldLabel}>
        <Text style={[styles.fieldLabelText, isDark && styles.fieldLabelTextDark]}>
          {label}
        </Text>
        {required ? (
          <Text style={styles.fieldRequired}>*</Text>
        ) : (
          <Text style={[styles.fieldOptional, isDark && styles.fieldOptionalDark]}>
            optional
          </Text>
        )}
      </View>
      <TextInput
        style={[
          styles.fieldInput,
          isDark && styles.fieldInputDark,
          focusedField === key && styles.fieldInputFocused,
        ]}
        placeholder={placeholder}
        placeholderTextColor={isDark ? COLORS.textFaintDark : COLORS.textFaint}
        value={state.status === 'ready' ? state.fields[key] : ''}
        onChangeText={(value) =>
          state.status === 'ready' &&
          dispatch({ type: 'SET_FIELD', key, value })
        }
        onFocus={() => setFocusedField(key)}
        onBlur={() => setFocusedField(null)}
        autoCapitalize="words"
        returnKeyType="next"
      />
    </View>
  );

  const serviceabilityBlocked =
    state.status === 'ready'
    && state.serviceabilityResult?.checked
    && state.serviceabilityResult.serviceable === false
    && (serviceabilityBlockCheckout ?? state.serviceabilityResult.block_checkout);

  const showMerchantServiceability =
    state.status === 'ready'
    && state.serviceabilityResult?.checked
    && state.serviceabilityResult.serviceable === false;

  const showIndiaPostInfo =
    state.status === 'ready'
    && !state.pincodeHasDelivery
    && state.serviceabilityResult?.serviceable !== true
    && !showMerchantServiceability
    && (state.serviceabilityResult?.show_india_post_delivery_warning ?? showIndiaPostDeliveryWarning);

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      style={{ flex: 1 }}
    >
      <ScrollView
        style={[{ flex: 1 }, isDark && { backgroundColor: COLORS.bgDark }]}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        {/* ── Step header ── */}
        <View style={[styles.stepHeader, isDark && styles.stepHeaderDark]}>
          <TouchableOpacity
            style={[styles.backBtn, isDark && styles.backBtnDark]}
            onPress={onBack}
            accessibilityLabel="Back to map"
            accessibilityRole="button"
          >
            <Text style={[styles.backBtnText, isDark && styles.backBtnTextDark]}>←</Text>
          </TouchableOpacity>
          <View style={styles.stepBadge}>
            <Text style={styles.stepBadgeText}>2</Text>
          </View>
          <View style={styles.stepText}>
            <Text style={[styles.stepTitle, isDark && styles.textLight]}>
              Add Address Details
            </Text>
            <Text style={[styles.stepSub, isDark && styles.textMutedStyle]}>
              Flat number and building info
            </Text>
          </View>
        </View>

        {/* ── DigiPin reference strip ── */}
        <View style={[styles.formDigipinStrip, isDark && styles.formDigipinStripDark]}>
          <Text style={styles.formDigipinStripIcon}>📍</Text>
          <Text style={styles.formDigipinStripLabel}>DigiPin</Text>
          <Text style={styles.formDigipinStripCode}>{digipin}</Text>
        </View>

        {/* ── Loading state ── */}
        {state.status === 'loading' ? (
          <View style={styles.loadingState} accessibilityLabel="Fetching address details">
            <ActivityIndicator size="large" color={COLORS.primary} />
            <Text style={[styles.loadingText, isDark && styles.loadingTextDark]}>
              Fetching address details…
            </Text>
          </View>
        ) : null}

        {/* ── Error state ── */}
        {state.status === 'error' ? (
          <View style={styles.errorState} accessibilityRole="alert">
            <Text style={styles.errorIcon}>⚠</Text>
            <Text style={[styles.errorMsg, isDark && styles.errorMsgDark]}>
              {state.message}
            </Text>
            <TouchableOpacity
              style={styles.btnSecondary}
              onPress={() => void fetchAdminInfo()}
              activeOpacity={0.8}
            >
              <Text style={styles.btnSecondaryText}>Retry</Text>
            </TouchableOpacity>
          </View>
        ) : null}

        {/* ── Main form ── */}
        {state.status === 'ready' ? (
          <View>
            {/* Auto-detected section */}
            <View style={[styles.sectionDivider, isDark && styles.sectionDividerDark]} />
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionHeaderIcon}>📍</Text>
              <Text style={[styles.sectionHeaderText, isDark && styles.sectionHeaderTextDark]}>
                Auto-detected from your digipin
              </Text>
            </View>

            <View style={styles.autoGrid}>
              {/* State & District in a row */}
              <View style={styles.autoRowsRow}>
                <View style={[styles.autoRow, styles.autoRowHalf]}>
                  <Text style={[styles.autoRowLabel, isDark && styles.autoRowLabelDark]}>
                    State
                  </Text>
                  <Text style={[styles.autoRowValue, isDark && styles.autoRowValueDark]}>
                    {state.adminInfo.state}
                  </Text>
                </View>
                <View style={[styles.autoRow, styles.autoRowHalf]}>
                  <Text style={[styles.autoRowLabel, isDark && styles.autoRowLabelDark]}>
                    District
                  </Text>
                  <Text style={[styles.autoRowValue, isDark && styles.autoRowValueDark]}>
                    {state.adminInfo.district}
                  </Text>
                </View>
              </View>

              {/* Locality */}
              <View style={styles.autoRow}>
                <Text style={[styles.autoRowLabel, isDark && styles.autoRowLabelDark]}>
                  Locality
                </Text>
                {state.localityOptions.length > 1 ? (
                  <TouchableOpacity
                    style={[
                      styles.localitySelector,
                      isDark && styles.localitySelectorDark,
                    ]}
                    onPress={() => setShowLocalityPicker(true)}
                    activeOpacity={0.8}
                    accessibilityRole="button"
                    accessibilityLabel="Select locality"
                  >
                    <Text
                      style={[
                        styles.localitySelectorText,
                        isDark && styles.localitySelectorTextDark,
                      ]}
                      numberOfLines={1}
                    >
                      {state.selectedLocality}
                    </Text>
                    <Text style={styles.localitySelectorArrow}>▼</Text>
                  </TouchableOpacity>
                ) : (
                  <Text style={[styles.autoRowValue, isDark && styles.autoRowValueDark]}>
                    {state.selectedLocality}
                  </Text>
                )}
              </View>

              {/* Pincode */}
              <View style={styles.autoRow}>
                <Text style={[styles.autoRowLabel, isDark && styles.autoRowLabelDark]}>
                  Pincode
                </Text>
                <Text style={styles.autoRowValuePincode}>{state.adminInfo.pincode}</Text>
              </View>
            </View>

            {showMerchantServiceability && state.serviceabilityResult ? (
              <View
                style={[
                  styles.pincodeBanner,
                  serviceabilityBlocked
                    ? styles.pincodeBannerError
                    : styles.pincodeBannerWarning,
                  isDark && (
                    serviceabilityBlocked
                      ? styles.pincodeBannerErrorDark
                      : styles.pincodeBannerDark
                  ),
                ]}
                accessibilityRole="text"
                accessibilityLabel={
                  serviceabilityBlocked
                    ? 'Delivery unavailable'
                    : 'Delivery may be limited'
                }
              >
                <Text style={styles.pincodeBannerIcon}>{serviceabilityBlocked ? '!' : '⚠'}</Text>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.pincodeBannerTitle, isDark && styles.pincodeBannerTitleDark]}>
                    {serviceabilityBlocked ? 'Delivery unavailable' : 'Delivery may be limited'}
                  </Text>
                  <Text style={[styles.pincodeBannerBody, isDark && styles.pincodeBannerBodyDark]}>
                    {state.serviceabilityResult.message
                      ?? (serviceabilityBlocked
                        ? 'This seller does not currently deliver to this pincode.'
                        : 'This seller recommends confirming delivery availability for this pincode.')}
                  </Text>
                </View>
              </View>
            ) : null}

            {showIndiaPostInfo ? (
              <View
                style={[
                  styles.pincodeBanner,
                  styles.pincodeBannerInfo,
                  isDark && styles.pincodeBannerInfoDark,
                ]}
                accessibilityRole="text"
                accessibilityLabel="India Post home-delivery information"
              >
                <Text style={styles.pincodeBannerIcon}>i</Text>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.pincodeBannerTitle, isDark && styles.pincodeBannerTitleDark]}>
                    India Post: no home-delivery office
                  </Text>
                  <Text style={[styles.pincodeBannerBody, isDark && styles.pincodeBannerBodyDark]}>
                    Courier partners may still deliver to this pincode.
                  </Text>
                </View>
              </View>
            ) : null}

            {/* Address label */}
            <View style={[styles.sectionDivider, isDark && styles.sectionDividerDark]} />
            <View style={[styles.sectionHeader, styles.sectionHeaderCompact]}>
              <Text
                style={[
                  styles.sectionHeaderText,
                  styles.sectionHeaderTextCompact,
                  isDark && styles.sectionHeaderTextDark,
                ]}
              >
                Save as
              </Text>
            </View>
            <View style={styles.labelPicker}>
              {(
                [
                  { value: 'home' as const, title: 'Home' },
                  { value: 'work' as const, title: 'Work' },
                  { value: 'other' as const, title: 'Other' },
                ] as const
              ).map(({ value, title }) => {
                const active = state.selectedLabel === value;
                const iconColor = active ? COLORS.primary : COLORS.textMuted;
                return (
                  <TouchableOpacity
                    key={value}
                    style={[
                      styles.labelPickerOption,
                      isDark && styles.labelPickerOptionDark,
                      active && styles.labelPickerOptionActive,
                      active && isDark && styles.labelPickerOptionActiveDark,
                    ]}
                    onPress={() => dispatch({ type: 'SET_LABEL', label: value })}
                    accessibilityRole="radio"
                    accessibilityState={{ checked: active }}
                    accessibilityLabel={title}
                    activeOpacity={0.97}
                  >
                    <AddressLabelIcon
                      label={value}
                      color={isDark && !active ? COLORS.textMutedDark : iconColor}
                    />
                    <Text
                      style={[
                        styles.labelPickerText,
                        isDark && styles.labelPickerTextDark,
                        active && styles.labelPickerTextActive,
                      ]}
                    >
                      {title}
                    </Text>
                  </TouchableOpacity>
                );
              })}
            </View>
            {state.selectedLabel === 'other' ? (
              <View style={styles.labelTextField}>
                <View style={styles.fieldLabel}>
                  <Text style={[styles.fieldLabelText, isDark && styles.fieldLabelTextDark]}>
                    Label name
                  </Text>
                  <Text style={styles.fieldRequired}>*</Text>
                </View>
                <TextInput
                  style={[
                    styles.fieldInput,
                    isDark && styles.fieldInputDark,
                  ]}
                  placeholder="e.g. Friend's home, Gym"
                  placeholderTextColor={isDark ? COLORS.textFaintDark : COLORS.textFaint}
                  value={state.labelText}
                  onChangeText={(value) =>
                    dispatch({ type: 'SET_LABEL_TEXT', value })
                  }
                  maxLength={64}
                  autoCapitalize="words"
                  returnKeyType="next"
                />
              </View>
            ) : null}

            {/* Manual entry section */}
            <View style={[styles.sectionDivider, isDark && styles.sectionDividerDark]} />
            <View style={styles.sectionHeader}>
              <AddressDetailsIcon
                color={isDark ? COLORS.textMutedDark : COLORS.textMuted}
                size={14}
              />
              <Text style={[styles.sectionHeaderText, isDark && styles.sectionHeaderTextDark]}>
                Your details
              </Text>
            </View>

            <View style={styles.fieldsGrid}>
              {/* Flat / House – required */}
              <View style={styles.fieldFull}>
                {renderField(
                  'flatNumber',
                  'Flat / House Number',
                  'e.g. 4B, Flat 201, House No. 12',
                  true
                )}
              </View>

              {/* Floor + Building in a row */}
              <View style={styles.fieldRow}>
                <View style={styles.field}>
                  {renderField('floorNumber', 'Floor', 'e.g. 3rd, Ground')}
                </View>
                <View style={styles.field}>
                  {renderField('buildingName', 'Building / Society', 'e.g. Sunshine Apts')}
                </View>
              </View>

              {/* Street – full width */}
              <View style={styles.fieldFull}>
                {renderField(
                  'streetName',
                  'Street / Area',
                  'e.g. MG Road, Sector 12'
                )}
              </View>
            </View>
          </View>
        ) : null}
      </ScrollView>

      {/* ── Sticky form actions ── */}
      {state.status === 'ready' ? (
        <View style={[styles.formActions, isDark && styles.formActionsDark]}>
          <TouchableOpacity
            style={[styles.btnGhost, isDark && styles.btnGhostDark]}
            onPress={onBack}
            activeOpacity={0.8}
          >
            <Text style={[styles.btnGhostText, isDark && styles.btnGhostTextDark]}>
              ← Adjust Pin
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.btnPrimary,
              { flex: 1 },
              (state.submitting || !state.fields.flatNumber.trim()
                || (state.selectedLabel === 'other' && !state.labelText.trim())
                || serviceabilityBlocked) && styles.btnDisabled,
            ]}
            onPress={handleSubmit}
            disabled={
              state.submitting
              || !state.fields.flatNumber.trim()
              || (state.selectedLabel === 'other' && !state.labelText.trim())
              || Boolean(serviceabilityBlocked)
            }
            activeOpacity={0.8}
            accessibilityRole="button"
            accessibilityLabel="Save address"
          >
            {state.submitting ? (
              <ActivityIndicator size="small" color="#fff" />
            ) : (
              <Text style={styles.btnPrimaryText}>Save Address  ✓</Text>
            )}
          </TouchableOpacity>
        </View>
      ) : null}

      {/* ── Locality picker modal ── */}
      {state.status === 'ready' && state.localityOptions.length > 1 ? (
        <Modal
          visible={showLocalityPicker}
          transparent
          animationType="slide"
          onRequestClose={() => setShowLocalityPicker(false)}
          accessibilityViewIsModal
        >
          <TouchableOpacity
            style={styles.modalOverlay}
            activeOpacity={1}
            onPress={() => setShowLocalityPicker(false)}
          >
            <TouchableOpacity
              style={[styles.modalSheet, isDark && styles.modalSheetDark]}
              activeOpacity={1}
            >
              <View style={styles.modalHandle} />
              <Text style={[styles.modalTitle, isDark && styles.modalTitleDark]}>
                Select Locality
              </Text>
              <FlatList
                data={state.localityOptions.map((name) => ({ name }))}
                keyExtractor={(item) => item.name}
                renderItem={({ item }) => {
                  const isSelected = item.name === state.selectedLocality;
                  return (
                    <TouchableOpacity
                      style={[
                        styles.modalOption,
                        isDark && styles.modalOptionDark,
                        isSelected && styles.modalOptionSelected,
                      ]}
                      onPress={() => {
                        if (state.status === 'ready') {
                          dispatch({ type: 'SET_LOCALITY', locality: item.name });
                        }
                        setShowLocalityPicker(false);
                      }}
                      activeOpacity={0.7}
                    >
                      <Text
                        style={[
                          styles.modalOptionText,
                          isDark && styles.modalOptionTextDark,
                          isSelected && styles.modalOptionTextSelected,
                        ]}
                      >
                        {item.name}
                      </Text>
                      {isSelected ? (
                        <Text style={styles.modalOptionCheckmark}>✓</Text>
                      ) : null}
                    </TouchableOpacity>
                  );
                }}
              />
            </TouchableOpacity>
          </TouchableOpacity>
        </Modal>
      ) : null}
    </KeyboardAvoidingView>
  );
};

export default AddressForm;
