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

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

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

  const [loading, setLoading] = useState(!!id);
  const [saving, setSaving] = useState(false);

  const [contactName, setContactName] = useState('');
  const [contactNo, setContactNo] = useState('');
  const [province, setProvince] = useState('');
  const [city, setCity] = useState('');
  const [district, setDistrict] = useState('');
  const [address, setAddress] = useState('');
  const [isDefault, setIsDefault] = useState(false);
  const [regionVisible, setRegionVisible] = useState(false);

  const handleRegionSelect = (p: string, c: string, d: string) => {
    setProvince(p);
    setCity(c);
    setDistrict(d);
  };

  const loadData = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    try {
      const list = await getAddressList();
      const item = list.find((a: Address) => a.id === id);
      if (item) {
        setContactName(item.contactName);
        setContactNo(item.contactNo);
        setProvince(item.province);
        setCity(item.city);
        setDistrict(item.district || '');
        setAddress(item.address);
        setIsDefault(item.defaultFlag === 1);
      }
    } catch (error) {
      console.error('加载地址失败:', error);
    }
    setLoading(false);
  }, [id]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const handleSave = async () => {
    if (!contactName.trim()) {
      Alert.alert('提示', '请输入收货人姓名');
      return;
    }
    if (!contactNo.trim()) {
      Alert.alert('提示', '请输入手机号码');
      return;
    }
    if (!province.trim() || !city.trim()) {
      Alert.alert('提示', '请输入省市信息');
      return;
    }
    if (!address.trim()) {
      Alert.alert('提示', '请输入详细地址');
      return;
    }

    setSaving(true);
    try {
      const params = {
        contactName: contactName.trim(),
        contactNo: contactNo.trim(),
        province: province.trim(),
        city: city.trim(),
        district: district.trim(),
        address: address.trim(),
        defaultFlag: isDefault ? 1 : 0,
      };

      let success = false;
      if (id) {
        success = await updateAddress({ id, ...params } as Address);
      } else {
        success = await addAddress(params);
      }

      if (success) {
        Alert.alert('成功', id ? '地址已更新' : '地址已添加', [
          { text: '确定', onPress: () => router.back() },
        ]);
      }
    } catch (error) {
      console.error('保存地址失败:', error);
      Alert.alert('错误', '保存失败');
    }
    setSaving(false);
  };

  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}>{id ? '编辑地址' : '新增地址'}</Text>
          <View style={styles.placeholder} />
        </View>

        <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
          <ImageBackground
            source={{ uri: Images.common.itemBg }}
            style={styles.formBg}
            resizeMode="stretch"
          >
            <View style={styles.form}>
              <View style={styles.formItem}>
                <Text style={styles.label}>收货人</Text>
                <TextInput
                  style={styles.input}
                  value={contactName}
                  onChangeText={setContactName}
                  placeholder="请输入收货人姓名"
                  placeholderTextColor="#999"
                />
              </View>

              <View style={styles.formItem}>
                <Text style={styles.label}>手机号码</Text>
                <TextInput
                  style={styles.input}
                  value={contactNo}
                  onChangeText={setContactNo}
                  placeholder="请输入手机号码"
                  placeholderTextColor="#999"
                  keyboardType="phone-pad"
                />
              </View>

              <View style={styles.formItem}>
                <Text style={styles.label}>所在地区</Text>
                <TouchableOpacity
                  style={styles.selector}
                  onPress={() => setRegionVisible(true)}
                >
                  <Text style={[styles.selectorText, !province && styles.placeholderText]}>
                    {province ? `${province} ${city} ${district}` : '请选择省/市/区'}
                  </Text>
                </TouchableOpacity>
              </View>

              <View style={styles.formItem}>
                <Text style={styles.label}>详细地址</Text>
                <TextInput
                  style={[styles.input, styles.textArea]}
                  value={address}
                  onChangeText={setAddress}
                  placeholder="请输入详细地址"
                  placeholderTextColor="#999"
                  multiline
                  numberOfLines={3}
                />
              </View>

              <View style={styles.switchItem}>
                <Text style={styles.switchLabel}>设为默认地址</Text>
                <Switch value={isDefault} onValueChange={setIsDefault} />
              </View>
            </View>
          </ImageBackground>
          <View style={{ height: 100 }} />
        </ScrollView>

        {/* 底部保存按钮 */}
        <View style={[styles.bottomBar, { paddingBottom: insets.bottom + 10 }]}>
          <TouchableOpacity
            style={[styles.saveBtn, saving && styles.saveBtnDisabled]}
            onPress={handleSave}
            disabled={saving}
            activeOpacity={0.8}
          >
            <ImageBackground
              source={{ uri: Images.common.loginBtn }}
              style={styles.saveBtnBg}
              resizeMode="stretch"
            >
              <Text style={styles.saveBtnText}>{saving ? '保存中...' : '保存'}</Text>
            </ImageBackground>
          </TouchableOpacity>
        </View>
      </ImageBackground>
      <RegionPicker
        visible={regionVisible}
        onClose={() => setRegionVisible(false)}
        onSelect={handleRegionSelect}
      />
    </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,
  },
  formBg: {
    margin: 15,
    padding: 15,
    borderRadius: 12,
    overflow: 'hidden',
  },
  form: {},
  formItem: {
    marginBottom: 15,
  },
  label: {
    color: '#333',
    fontSize: 14,
    marginBottom: 8,
  },
  input: {
    backgroundColor: 'rgba(255,255,255,0.8)',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 12,
    color: '#333',
    fontSize: 14,
  },
  selector: {
    backgroundColor: 'rgba(255,255,255,0.8)',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 12,
  },
  selectorText: {
    fontSize: 14,
    color: '#333',
  },
  placeholderText: {
    color: '#999',
  },
  textArea: {
    height: 80,
    textAlignVertical: 'top',
  },
  switchItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 10,
  },
  switchLabel: {
    color: '#333',
    fontSize: 14,
  },
  bottomBar: {
    paddingHorizontal: 15,
    paddingTop: 10,
  },
  saveBtn: {
    height: 50,
    overflow: 'hidden',
  },
  saveBtnBg: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  saveBtnDisabled: {
    opacity: 0.6,
  },
  saveBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});
