import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import React, { useCallback, useState } from 'react';
import {
    ActivityIndicator,
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { Address, deleteAddress, getAddressList, updateAddress } from '@/services/address';

export default function AddressListScreen() {
  const { type } = useLocalSearchParams<{ type?: string }>();
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<Address[]>([]);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const data = await getAddressList();
      setList(data);
    } catch (error) {
      console.error('加载地址失败:', error);
    }
    setLoading(false);
  }, []);

  useFocusEffect(
    useCallback(() => {
      loadData();
    }, [loadData])
  );

  // 选择地址
  const selectAddress = (item: Address) => {
    if (type === '1') {
      // 从结算页面来，选择后返回
      router.back();
      // 通过全局事件传递选中的地址
    }
  };

  // 设为默认
  const setDefault = async (item: Address) => {
    try {
      await updateAddress({ ...item, defaultFlag: 1 });
      loadData();
    } catch (error) {
      console.error('设置默认地址失败:', error);
    }
  };

  // 删除地址
  const handleDelete = (item: Address) => {
    Alert.alert('提示', '确定删除该地址吗？', [
      { text: '取消', style: 'cancel' },
      {
        text: '删除',
        style: 'destructive',
        onPress: async () => {
          try {
            await deleteAddress(item.id);
            loadData();
          } catch (error) {
            console.error('删除地址失败:', error);
          }
        },
      },
    ]);
  };

  // 编辑地址
  const editAddress = (item: Address) => {
    router.push(`/address/edit?id=${item.id}` as any);
  };

  // 新增地址
  const addNewAddress = () => {
    router.push('/address/edit' as any);
  };

  const goBack = () => {
    router.back();
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#fff" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground
        source={{ uri: Images.mine.kaixinMineBg }}
        style={styles.background}
        resizeMode="cover"
      >
        {/* 顶部导航 */}
        <View style={[styles.header, { paddingTop: insets.top }]}>
          <TouchableOpacity style={styles.backBtn} onPress={goBack}>
            <Text style={styles.backText}>←</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle}>收货地址</Text>
          <View style={styles.placeholder} />
        </View>

        <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
          {list.length === 0 ? (
            <View style={styles.emptyContainer}>
              <Text style={styles.emptyText}>暂无收货地址</Text>
            </View>
          ) : (
            list.map((item) => (
              <TouchableOpacity
                key={item.id}
                style={styles.addressItem}
                onPress={() => selectAddress(item)}
              >
                <ImageBackground
                  source={{ uri: Images.common.itemBg }}
                  style={styles.addressItemBg}
                  resizeMode="stretch"
                >
                  <View style={styles.addressInfo}>
                    <View style={styles.nameRow}>
                      <Text style={styles.name}>{item.contactName}</Text>
                      <Text style={styles.phone}>{item.contactNo}</Text>
                      {item.defaultFlag === 1 && (
                        <View style={styles.defaultTag}>
                          <Text style={styles.defaultText}>默认</Text>
                        </View>
                      )}
                    </View>
                    <Text style={styles.addressDetail}>
                      {item.province}{item.city}{item.district}{item.address}
                    </Text>
                  </View>
                  <View style={styles.actions}>
                    {item.defaultFlag !== 1 && (
                      <TouchableOpacity style={styles.actionBtn} onPress={() => setDefault(item)}>
                        <Text style={styles.actionText}>设为默认</Text>
                      </TouchableOpacity>
                    )}
                    <TouchableOpacity style={styles.actionBtn} onPress={() => editAddress(item)}>
                      <Text style={styles.actionText}>编辑</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.actionBtn} onPress={() => handleDelete(item)}>
                      <Text style={[styles.actionText, styles.deleteText]}>删除</Text>
                    </TouchableOpacity>
                  </View>
                </ImageBackground>
              </TouchableOpacity>
            ))
          )}
          <View style={{ height: 100 }} />
        </ScrollView>

        {/* 底部新增按钮 */}
        <View style={[styles.bottomBar, { paddingBottom: insets.bottom + 10 }]}>
          <TouchableOpacity style={styles.addBtn} onPress={addNewAddress} activeOpacity={0.8}>
            <ImageBackground
              source={{ uri: Images.common.loginBtn }}
              style={styles.addBtnBg}
              resizeMode="stretch"
            >
              <Text style={styles.addBtnText}>+ 新增收货地址</Text>
            </ImageBackground>
          </TouchableOpacity>
        </View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: '#1a1a2e',
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    paddingBottom: 10,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backText: {
    color: '#fff',
    fontSize: 24,
  },
  headerTitle: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
    paddingHorizontal: 15,
  },
  emptyContainer: {
    paddingTop: 100,
    alignItems: 'center',
  },
  emptyText: {
    color: '#999',
    fontSize: 14,
  },
  addressItem: {
    marginTop: 10,
  },
  addressItemBg: {
    padding: 15,
    borderRadius: 12,
    overflow: 'hidden',
  },
  addressInfo: {
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0,0,0,0.1)',
    paddingBottom: 12,
  },
  nameRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  name: {
    color: '#333',
    fontSize: 16,
    fontWeight: '600',
  },
  phone: {
    color: '#333',
    fontSize: 14,
    marginLeft: 15,
  },
  defaultTag: {
    backgroundColor: '#ff6b00',
    borderRadius: 10,
    paddingHorizontal: 8,
    paddingVertical: 2,
    marginLeft: 10,
  },
  defaultText: {
    color: '#fff',
    fontSize: 10,
  },
  addressDetail: {
    color: '#666',
    fontSize: 13,
    marginTop: 8,
    lineHeight: 18,
  },
  actions: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    paddingTop: 12,
  },
  actionBtn: {
    paddingHorizontal: 12,
    paddingVertical: 6,
  },
  actionText: {
    color: '#666',
    fontSize: 13,
  },
  deleteText: {
    color: '#ff4d4f',
  },
  bottomBar: {
    paddingHorizontal: 15,
    paddingTop: 10,
  },
  addBtn: {
    height: 50,
    overflow: 'hidden',
  },
  addBtnBg: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  addBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});
