import AsyncStorage from '@react-native-async-storage/async-storage';
import { useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import {
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Switch,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { useAuth } from '@/contexts/AuthContext';
import { logoff } from '@/services/user';

export default function SettingScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { logout } = useAuth();
  
  const [animalChecked, setAnimalChecked] = useState(true);
  const [vibratorChecked, setVibratorChecked] = useState(true);

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

  const loadSettings = async () => {
    try {
      const animal = await AsyncStorage.getItem('closeAnimal');
      const vibrator = await AsyncStorage.getItem('closeVibrator');
      setAnimalChecked(animal !== 'true');
      setVibratorChecked(vibrator !== 'true');
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  };

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

  const handleAnimalChange = async (value: boolean) => {
    setAnimalChecked(value);
    await AsyncStorage.setItem('closeAnimal', (!value).toString());
  };

  const handleVibratorChange = async (value: boolean) => {
    setVibratorChecked(value);
    await AsyncStorage.setItem('closeVibrator', (!value).toString());
  };

  const handleLogout = () => {
    Alert.alert('提示', '确定要退出登录吗?', [
      { text: '取消', style: 'cancel' },
      {
        text: '确定',
        onPress: async () => {
          await logout();
          router.back();
        }
      }
    ]);
  };

  const handleLogoff = () => {
    Alert.alert('提示', '确定要注销当前账号吗?', [
      { text: '取消', style: 'cancel' },
      {
        text: '确定',
        style: 'destructive',
        onPress: async () => {
          try {
            const res = await logoff();
            if (res) {
              await logout();
              router.back();
            }
          } catch (error) {
            console.error('注销失败:', error);
            Alert.alert('提示', '注销失败');
          }
        }
      }
    ]);
  };

  const handleShowAgreement = (type: string) => {
    const agreementType = type === 'user' ? 'user.html' : 'privacy.html';
    console.log('跳转到协议页面:', agreementType);
    router.push(`/agreement?type=${agreementType}` as any);
  };

  return (
    <ImageBackground
      source={{ uri: Images.mine.kaixinMineBg }}
      style={styles.container}
      resizeMode="cover"
    >
      <StatusBar barStyle="light-content" />
      
      {/* 顶部导航 */}
      <View style={[styles.header, { paddingTop: insets.top }]}>
        <TouchableOpacity style={styles.backBtn} onPress={handleBack}>
          <Text style={styles.backIcon}>‹</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>设置</Text>
        <View style={styles.placeholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 通知设置 */}
        <Text style={styles.sectionTitle}>通知</Text>
        <View style={styles.card}>
          <View style={styles.menuItem}>
            <Text style={styles.menuText}>开箱动画</Text>
            <Switch
              value={animalChecked}
              onValueChange={handleAnimalChange}
              trackColor={{ false: '#e0e0e0', true: '#FC7D2E' }}
              thumbColor="#fff"
            />
          </View>
          <View style={styles.divider} />
          <View style={styles.menuItem}>
            <Text style={styles.menuText}>开箱震动</Text>
            <Switch
              value={vibratorChecked}
              onValueChange={handleVibratorChange}
              trackColor={{ false: '#e0e0e0', true: '#FC7D2E' }}
              thumbColor="#fff"
            />
          </View>
        </View>

        {/* 关于 */}
        <Text style={styles.sectionTitle}>关于</Text>
        <View style={styles.card}>
          <TouchableOpacity 
            style={styles.menuItem}
            onPress={() => handleShowAgreement('user')}
          >
            <Text style={styles.menuText}>用户协议</Text>
            <Text style={styles.arrow}>›</Text>
          </TouchableOpacity>
          <View style={styles.divider} />
          <TouchableOpacity 
            style={styles.menuItem}
            onPress={() => handleShowAgreement('privacy')}
          >
            <Text style={styles.menuText}>隐私协议</Text>
            <Text style={styles.arrow}>›</Text>
          </TouchableOpacity>
        </View>

        {/* 登录相关按钮 - 始终显示 */}
        <View style={styles.btnSection}>
          <TouchableOpacity style={styles.logoutBtn} onPress={handleLogout}>
            <Text style={styles.logoutBtnText}>退出登录</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.logoffBtn} onPress={handleLogoff}>
            <Text style={styles.logoffBtnText}>注销账号</Text>
          </TouchableOpacity>
        </View>

        <View style={{ height: 50 }} />
      </ScrollView>
    </ImageBackground>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    height: 80,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backIcon: {
    fontSize: 32,
    color: '#fff',
    fontWeight: 'bold',
  },
  headerTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
    paddingHorizontal: 15,
  },
  sectionTitle: {
    fontSize: 14,
    color: '#fff',
    marginTop: 20,
    marginBottom: 10,
    marginLeft: 5,
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: 10,
    overflow: 'hidden',
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    paddingVertical: 15,
  },
  menuText: {
    fontSize: 14,
    color: '#666',
  },
  arrow: {
    fontSize: 20,
    color: '#ccc',
  },
  divider: {
    height: 1,
    backgroundColor: '#f0f0f0',
    marginLeft: 15,
  },
  btnSection: {
    marginTop: 30,
    paddingHorizontal: 20,
  },
  logoutBtn: {
    backgroundColor: '#FC7D2E',
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 15,
  },
  logoutBtnText: {
    fontSize: 16,
    color: '#fff',
  },
  logoffBtn: {
    backgroundColor: 'transparent',
    height: 44,
    borderRadius: 22,
    borderWidth: 1,
    borderColor: '#999',
    justifyContent: 'center',
    alignItems: 'center',
  },
  logoffBtnText: {
    fontSize: 16,
    color: '#999',
  },
});
