import React, { useState, useMemo, useRef, useCallback, useEffect } from 'react';
import { TouchableOpacity, Vibration, TextInput, StyleSheet } from 'react-native';
import { router } from 'expo-router';
import { View, XStack } from 'tamagui';
import { useAppStore } from '@/stores';
import CustomText from '@/components/common/CustomText.jsx';
import processedCountryCode from '@/constants/processedCountryCode.js';
import { CustomHeader } from '@/components/common/CustomHeader';
import { FlashList } from '@shopify/flash-list';
import SearchIcon from '@/assets/images/svg/search.svg';
import { useAuthStore } from '@/stores/auth';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { wp } from '@/utils/ui/screenUtils';
import { useTranslation } from '@/node_modules/react-i18next';

// --- 常量定义 ---
const HEADER_HEIGHT = wp(32);
const ITEM_HEIGHT = wp(44);

// 预处理国家数据（模块级单次执行）
// 为每一项添加必要的 UI 属性，避免在渲染时重复计算
const processedCountries = processedCountryCode.map(country => ({
  ...country,
  type: 'item',
  isCommon: false
}));

// 常用地区数据
const commonRegions = [
  { cn: '中国大陆', code: 'CN', zone: '86', en: 'China', tw: '中國', isCommon: true, pinyinFirst: 'Z', type: 'item' },
  { cn: '中国香港', code: 'HK', zone: '852', en: 'Hong Kong', tw: '香港', isCommon: true, pinyinFirst: 'Z', type: 'item' },
  { cn: '中国澳门', code: 'MO', zone: '853', en: 'Macao', tw: '澳門', isCommon: true, pinyinFirst: 'Z', type: 'item' },
  { cn: '中国台湾', code: 'TW', zone: '886', en: 'Taiwan', tw: '台灣', isCommon: true, pinyinFirst: 'Z', type: 'item' }
];

// --- 纯函数数据处理 ---
const filterAndGroupData = (searchText, t, langField) => {
  const result = [];
  const indices = [];
  const titles = [];
  const isSearching = !!searchText?.trim();
  const searchLower = isSearching ? searchText.toLowerCase() : '';
  const commonTitle = t('region.common');

  // 1. 常用地区（仅非搜索状态显示）
  if (!isSearching && commonRegions.length > 0) {
    indices.push(result.length);
    titles.push(commonTitle);
    result.push({ type: 'header', title: commonTitle, id: 'header-common' });
    // 为常用地区添加 displayName
    result.push(...commonRegions.map(item => ({ ...item, displayName: item[langField] || item.cn })));
  }

  // 2. 过滤数据
  let targetData = processedCountries;
  if (isSearching) {
    targetData = processedCountries.filter(country => 
      country.searchText.includes(searchLower) || (country[langField] && country[langField].includes(searchText))
    );
  }

  // 3. 分组逻辑
  const groupedMap = new Map();
  targetData.forEach(country => {
    let letter;
    if (langField === 'en') {
      // 英文环境使用英文首字母
      letter = country.en ? country.en.charAt(0).toUpperCase() : '#';
    } else {
      const first = country.pinyinFirst ? country.pinyinFirst.trim().charAt(0) : '';
      letter = first ? first.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toUpperCase() : '#';
    }
    
    // 确保是 A-Z，否则归为 #
    if (!/^[A-Z]$/.test(letter)) {
      letter = '#';
    }

    if (!groupedMap.has(letter)) {
      groupedMap.set(letter, []);
    }
    // 添加 displayName
    groupedMap.get(letter).push({ ...country, displayName: country[langField] || country.cn });
  });

  // 4. 构建扁平列表
  // 预先排序 keys 避免多次 sort
  const sortedKeys = Array.from(groupedMap.keys()).sort((a, b) => {
    if (a === '#') return 1;
    if (b === '#') return -1;
    return a.localeCompare(b);
  });
  
  sortedKeys.forEach(letter => {
    const items = groupedMap.get(letter);
    // 组内排序
    items.sort((a, b) => a.displayName.localeCompare(b.displayName));
    
    if (items.length > 0) {
      indices.push(result.length);
      titles.push(letter);
      result.push({ type: 'header', title: letter, id: `header-${letter}` });
      result.push(...items);
    }
  });

  return { flashListData: result, stickyHeaderIndices: indices, headerTitles: titles, commonTitle };
};

// --- 子组件 ---

const HeaderRow = React.memo(({ title }) => (
  <View style={styles.headerRow}>
    <CustomText style={styles.headerText}>{title}</CustomText>
  </View>
));

const CountryRow = React.memo(({ item, onPress }) => (
  <TouchableOpacity
    onPress={() => onPress(item)}
    style={styles.countryRow}
    activeOpacity={0.6}
  >
    <CustomText style={styles.countryName}>{item.displayName}</CustomText>
    <View style={styles.zoneContainer}>
      <CustomText style={styles.zoneText}>+{item.zone}</CustomText>
    </View>
  </TouchableOpacity>
));

const AlphabetIndexBar = React.memo(({ titles, onSelect, primaryColor, commonTitle }) => {
  if (!titles || titles.length === 0) return null;
  
  // 过滤掉 '常用' 用于显示索引
  const letters = titles.filter(t => t !== commonTitle);
  
  return (
    <View style={styles.indexBar}>
      {letters.map((letter) => (
        <TouchableOpacity
          key={letter}
          onPress={() => onSelect(letter)}
          style={styles.indexItem}
          activeOpacity={0.6}
          hitSlop={{ top: 4, bottom: 4, left: 10, right: 10 }}
        >
          <CustomText style={[styles.indexText, { color: primaryColor }]}>
            {letter}
          </CustomText>
        </TouchableOpacity>
      ))}
    </View>
  );
});

const SearchBar = React.memo(({ value, onChange, placeholder }) => (
  <View style={styles.searchContainer}>
    <XStack alignItems="center" style={styles.searchBox}>
      <SearchIcon width={wp(16)} height={wp(16)} />
      <TextInput
        placeholder={placeholder}
        value={value}
        onChangeText={onChange}
        placeholderTextColor="#999"
        style={styles.searchInput}
        returnKeyType="search"
        clearButtonMode="while-editing"
      />
    </XStack>
  </View>
));

// --- 主组件 ---

export default function RegionScreen() {
  const { setSelectedRegion } = useAuthStore();
  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText, setDebouncedSearchText] = useState('');
  const flashListRef = useRef(null);
  const insets = useSafeAreaInsets();
  const primaryColor = useAppStore(s => s.primary) ?? '#007AFF';
  const { t, i18n } = useTranslation();

  // 获取当前语言对应的字段名
  const langField = useMemo(() => {
    const lang = i18n.language;
    if (lang === 'zh-TW' || lang === 'zh-HK') return 'tw';
    if (lang === 'en') return 'en';
    return 'cn';
  }, [i18n.language]);

  // 自定义防抖 Hook
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchText(searchText);
    }, 200);
    return () => clearTimeout(timer);
  }, [searchText]);

  // 数据计算
  const { flashListData, stickyHeaderIndices, headerTitles, commonTitle } = useMemo(
    () => filterAndGroupData(debouncedSearchText, t, langField),
    [debouncedSearchText, t, langField]
  );

  // 搜索重置滚动逻辑
  useEffect(() => {
    if (flashListRef.current) {
      flashListRef.current.scrollToOffset({ offset: 0, animated: false });
    }
  }, [debouncedSearchText]);

  // 回调函数
  const handleCountrySelect = useCallback((country) => {
    setSelectedRegion(country);
    router.back();
  }, [setSelectedRegion]);

  const scrollToLetter = useCallback((letter) => {
    const index = flashListData.findIndex(item => item.type === 'header' && item.title === letter);
    if (index !== -1 && flashListRef.current) {
      flashListRef.current.scrollToIndex({ index, animated: true });
      Vibration.cancel();
    }
  }, [flashListData]);

  const renderItem = useCallback(({ item }) => {
    if (item.type === 'header') return <HeaderRow title={item.title} />;
    return <CountryRow item={item} onPress={handleCountrySelect} />;
  }, [handleCountrySelect]);

  const getItemType = useCallback((item) => item.type, []);

  const keyExtractor = useCallback((item) => {
    return item.type === 'header' ? item.id : item.code;
  }, []);

  const overrideItemLayout = useCallback((layout, item) => {
    layout.size = item.type === 'header' ? HEADER_HEIGHT : ITEM_HEIGHT;
    layout.span = 1;
  }, []);

  return (
    <View flex={1}>
      <CustomHeader title={t('region.title')} onBack={() => router.back()} />
      
      <View flex={1} style={styles.container}>
        <SearchBar 
          value={searchText} 
          onChange={setSearchText} 
          placeholder={t('region.searchPlaceholder')}
        />
        
        <View style={styles.listContainer}>
          <FlashList
            ref={flashListRef}
            key={debouncedSearchText?.trim() ? 'search-mode' : 'normal-mode'}
            data={flashListData}
            renderItem={renderItem}
            getItemType={getItemType}
            estimatedItemSize={wp(44)}
            keyExtractor={keyExtractor}
            contentContainerStyle={{ paddingBottom: insets.bottom }}
            bounces={false}
            alwaysBounceVertical={false}
            overScrollMode="never"
            stickyHeaderIndices={stickyHeaderIndices}
            overrideItemLayout={overrideItemLayout}
            removeClippedSubviews={true}
            keyboardShouldPersistTaps="handled"
          />
        </View>
        
        <AlphabetIndexBar 
          titles={headerTitles} 
          onSelect={scrollToLetter} 
          primaryColor={primaryColor}
          commonTitle={commonTitle}
        />
      </View>
    </View>
  );
}

// --- 样式定义 ---
const styles = StyleSheet.create({
  container: {
    position: 'relative',
    flex: 1,
  },
  headerRow: {
    backgroundColor: '#F5F5F5',
    paddingHorizontal: wp(30),
    height: HEADER_HEIGHT,
    justifyContent: 'center',
  },
  headerText: {
    fontSize: wp(14),
    color: '#666666',
    fontFamily: 'Bold',
    includeFontPadding: false,
    textAlignVertical: 'center',
  },
  countryRow: {
    paddingHorizontal: wp(30),
    height: ITEM_HEIGHT,
    borderBottomWidth: wp(1),
    borderBottomColor: '#F0F0F0',
    backgroundColor: 'white',
    justifyContent: 'center',
  },
  countryName: {
    fontSize: wp(14),
    color: '#191919',
    fontFamily: 'Medium',
    paddingRight: wp(64),
  },
  zoneContainer: {
    position: 'absolute',
    right: wp(45),
    top: 0,
    bottom: 0,
    justifyContent: 'center',
  },
  zoneText: {
    fontSize: wp(14),
    color: '#939393',
    fontFamily: 'Medium',
  },
  searchContainer: {
    paddingHorizontal: wp(16),
    backgroundColor: '#fff',
    paddingTop: wp(10),
    paddingBottom: wp(10),
  },
  searchBox: {
    backgroundColor: '#F5F5F5',
    borderRadius: wp(4),
    paddingHorizontal: wp(12),
    height: wp(33),
  },
  searchInput: {
    flex: 1,
    height: wp(33),
    fontSize: wp(14),
    backgroundColor: 'transparent',
    paddingVertical: 0,
    marginLeft: wp(8),
  },
  listContainer: {
    flex: 1,
    position: 'relative',
  },
  indexBar: {
    position: 'absolute',
    right: wp(8),
    top: '55%',
    transform: [{ translateY: '-50%' }],
    paddingVertical: wp(8),
    paddingHorizontal: wp(4),
    zIndex: 1000,
  },
  indexItem: {
    paddingVertical: wp(2),
    paddingHorizontal: wp(6),
    minHeight: wp(25),
    justifyContent: 'center',
    alignItems: 'center',
  },
  indexText: {
    fontSize: wp(12),
    fontFamily: 'Medium',
    textAlign: 'center',
  },
});
