import React, { useState, useEffect } from 'react';
import { 
  StyleSheet, 
  ScrollView, 
  Image, 
  View, 
  TouchableOpacity,
  ImageBackground,
  Alert 
} from 'react-native';
import { Text, Button } from '@ui-kitten/components';
import { useNavigation } from '@react-navigation/native';

import { useAuth } from '../context/AuthContext';
import { rpx } from '../utils/rpx';
import { apiService } from '../utils/api'; 
import { auth } from '../utils/auth';
const ProfileScreen = () => {
  const navigation = useNavigation();
  const { setIsLoggedIn } = useAuth();
  const [userInfo, setUserInfo] = useState({});

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

  const formatName = (name) => {
    if (!name) return '';
    return name.charAt(0) + '*'.repeat(name.length - 1);
  };

  const getUserInfo = async () => {
    try {
      const response = await apiService.getUserInfo();
      if (response.code === 200) {
        setUserInfo(response.user);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  };

  const handleLogout = async () => {
    try {
      await auth.removeToken(); // 清除本地存储的 token
      // setIsLoggedIn(false); // 更新登录状态
      // 不需要手动导航，因为 AppNavigator 会根据 isLoggedIn 自动处理导航
      getUserInfo();
    } catch (error) {
      console.error('退出登录失败:', error);
    }
  };

  return (
    <ImageBackground 
      source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uYRs7Cv2Pbp95w3KjGO3' }}
      style={styles.background}
    >
      <ScrollView style={styles.scrollView}>
        <View style={styles.page}>
          {/* 头部区域 */}
          <View style={styles.header}>
            <View style={styles.headerLeft}>
              <Image
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u3giTY4VkWYpnGWRuFHF' }}
                style={styles.avatar}
              />
              <View style={styles.userinfo}>
                <Text style={styles.username}>
                  {formatName(userInfo.realName)}
                </Text>
                <Text style={styles.userphone}>
                  {userInfo.phonenumber}
                </Text>
              </View>
            </View>
            <TouchableOpacity 
              style={styles.headerRight}
              onPress={() => navigation.navigate('BindIndex')}
            >
              <Image
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uyb0iFo50FJ0MZg3RKkV' }}
                style={styles.code}
              />
            </TouchableOpacity>
          </View>

          {/* 管理与服务区域 */}
          <Text style={styles.tit}>管理与服务</Text>
          <View style={styles.content}>
            {/* <TouchableOpacity 
              style={styles.item}
              onPress={() => navigation.navigate('OrderList')}
            >
              <Image
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uVEbrRDbZXvELwK73KAi' }}
                style={styles.itemIcon}
              />
              <Text style={styles.itemText}>我的订单</Text>
            </TouchableOpacity> */}

            <TouchableOpacity 
              style={styles.item}
              onPress={() => navigation.navigate('HelpCenter')}
            >
              <Image
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uO1ju1OpuA5jjMR7bLYh' }}
                style={styles.itemIcon}
              />
              <Text style={styles.itemText}>帮助和客服</Text>
            </TouchableOpacity>

            <TouchableOpacity 
              style={styles.item}
              onPress={() => navigation.navigate('Feedback')}
            >
              <Image
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uHNMNwTRw89NhtgZUNXK' }}
                style={styles.itemIcon}
              />
              <Text style={styles.itemText}>意见和反馈</Text>
            </TouchableOpacity>

            {userInfo.isAuthentication === false && (
              <TouchableOpacity 
                style={styles.item}
                onPress={() => navigation.navigate('IdVerification')}
              >
                <Image
                  source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/unrltNyYYRXUutaqtuJY' }}
                  style={styles.itemIcon}
                />
                <Text style={styles.itemText}>实名认证</Text>
              </TouchableOpacity>
            )}

            {/* {userInfo.userType === '02' && (
              <TouchableOpacity 
                style={[styles.item, styles.lastItem]}
                onPress={() => navigation.navigate('MerchantPortal')}
              >
                <Image
                  source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u1SsqJYSQ8jTK9PkhFtF' }}
                  style={styles.itemIcon}
                />
                <Text style={styles.itemText}>商户端</Text>
              </TouchableOpacity>
            )} */}
          </View>

          {/* 退出登录按钮 */}
          <Button
            style={styles.logoutButton}
            status='danger'
            onPress={handleLogout}
          >
            退出登录
          </Button>
        </View>
      </ScrollView>
    </ImageBackground>
  );
};

const styles = StyleSheet.create({
  background: {
    flex: 1,
    width: '100%',
  },
  scrollView: {
    flex: 1,
  },
  page: {
    flex: 1,
    paddingTop: rpx(200),
    paddingHorizontal: rpx(32),
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: rpx(108),
    height: rpx(108),
    borderRadius: rpx(54),
  },
  userinfo: {
    marginLeft: rpx(40),
  },
  username: {
    fontWeight: '700',
    fontSize: rpx(36),
    color: '#3D3D3D',
  },
  userphone: {
    fontWeight: '400',
    fontSize: rpx(28),
    color: '#3D3D3D',
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  code: {
    width: rpx(40),
    height: rpx(40),
  },
  tit: {
    marginTop: rpx(40),
    fontWeight: '700',
    fontSize: rpx(36),
    color: '#3D3D3D',
  },
  content: {
    marginTop: rpx(24),
    width: rpx(688),
    padding: rpx(42),
    backgroundColor: '#FFFFFF',
    borderRadius: rpx(30),
  },
  item: {
    width: '100%',
    paddingVertical: rpx(34),
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#D8D8D8',
  },
  lastItem: {
    borderBottomWidth: 0,
  },
  itemIcon: {
    width: rpx(38),
    height: rpx(38),
    marginTop: rpx(4),
    marginRight: rpx(34),
  },
  itemText: {
    fontWeight: '400',
    fontSize: rpx(32),
    color: '#3D3D3D',
  },
  logoutButton: {
    marginTop: rpx(40),
    marginBottom: rpx(40),
    borderRadius: rpx(30),
  }
});

export default ProfileScreen;