import * as Clipboard from 'expo-clipboard';
import { Image } from 'expo-image';
import { useFocusEffect, useRouter } from 'expo-router';
import React, { useCallback, useState } from 'react';
import {
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { MenuCell } from '@/components/mine/MenuCell';
import { Images } from '@/constants/images';
import { getMagicIndex } from '@/services/award';
import { getParamConfig, getUserInfo, UserInfo } from '@/services/user';

interface IndexData {
  couponCount?: number;
  inventoryCount?: number;
  magicBalance?: number;
  treasureBoxCount?: number;
}

export default function MineScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [indexData, setIndexData] = useState<IndexData | null>(null);
  const [inviteShow, setInviteShow] = useState(false);
  const [showCredit, setShowCredit] = useState(false);
  const [filingInfo, setFilingInfo] = useState<{ state: number; data: string } | null>(null);
  const [showWallet, setShowWallet] = useState(false);

  const loadData = useCallback(async () => {
    try {
      const [info, magicData] = await Promise.all([
        getUserInfo(),
        getMagicIndex(),
      ]);
      setUserInfo(info);
      setIndexData(magicData);

      // 获取邀请配置
      const inviteConfig = await getParamConfig('invite_config');
      setInviteShow(inviteConfig?.state !== 0);

      // 获取积分显示配置
      const creditConfig = await getParamConfig('credit_show');
      setShowCredit(creditConfig?.state !== 0);

      // 获取备案信息
      const filingConfig = await getParamConfig('beian_icp');
      if (filingConfig) {
        setFilingInfo({ state: filingConfig.state, data: filingConfig.data });
      }

      // 获取钱包显示配置
      const walletConfig = await getParamConfig('wallet_recharge_show');
      setShowWallet(walletConfig?.state === 1);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  }, []);

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

  const handleLogin = () => {
    if (!userInfo) {
      router.push('/login' as any);
    }
  };

  const handleCopy = async (text: string) => {
    await Clipboard.setStringAsync(text);
    Alert.alert('提示', '复制成功');
  };

  const handleMenuPress = (route: string) => {
    if (!userInfo) {
      router.push('/login' as any);
      return;
    }
    if (route) {
      router.push(route as any);
    }
  };

  const handleMenuItemPress = (type: string) => {
    if (!userInfo && type !== '4_4') {
      router.push('/login' as any);
      return;
    }

    switch (type) {
      case '1_1': // 钱包
        router.push('/wallet' as any);
        break;
      case '2_0': // 全部订单
        router.push('/orders' as any);
        break;
      case '6_1': // 兑换码
        Alert.alert('提示', '兑换码功能');
        break;
      case '4_4': // 联系客服
        Alert.alert('联系客服', '客服时间：10:00 ~ 18:00');
        break;
      case '4_3': // 地址
        router.push('/address' as any);
        break;
      case '4_9': // 意见反馈
        Alert.alert('提示', '意见反馈功能');
        break;
      case '4_5': // 设置
        Alert.alert('提示', '设置功能');
        break;
      default:
        break;
    }
  };

  const showNumber = (key: keyof IndexData) => {
    if (!indexData) return '-';
    const val = indexData[key];
    if (typeof val === 'undefined') return '-';
    return String(val);
  };

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground
        source={{ uri: Images.mine.kaixinMineBg }}
        style={styles.background}
        resizeMode="cover"
      >
        {/* 顶部背景 */}
        <Image
          source={{ uri: Images.mine.kaixinMineHeadBg }}
          style={[styles.headerBg, { top: 0 }]}
          contentFit="cover"
        />

        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={{ paddingTop: insets.top }}
          showsVerticalScrollIndicator={false}
        >
          {/* 顶部标题 */}
          <View style={styles.header}>
            <Text style={styles.title}>个人中心</Text>
          </View>

          {/* 用户信息 */}
          <TouchableOpacity
            style={styles.userBox}
            onPress={handleLogin}
            activeOpacity={0.8}
          >
            <ImageBackground
              source={{ uri: Images.common.defaultAvatar }}
              style={styles.avatarBox}
              resizeMode="cover"
            >
              {userInfo?.avatar && (
                <Image
                  source={{ uri: userInfo.avatar }}
                  style={styles.avatar}
                  contentFit="cover"
                />
              )}
            </ImageBackground>
            <View style={styles.userInfo}>
              <View style={styles.nicknameRow}>
                <Text style={styles.nickname}>
                  {userInfo?.nickname || '暂未登录！'}
                </Text>
                {userInfo && (
                  <TouchableOpacity onPress={() => handleMenuPress('/user-info')}>
                    <Image
                      source={{ uri: Images.mine.editIcon }}
                      style={styles.editIcon}
                      contentFit="contain"
                    />
                  </TouchableOpacity>
                )}
              </View>
              {userInfo ? (
                <View style={styles.idRow}>
                  <TouchableOpacity
                    style={styles.idItem}
                    onPress={() => handleCopy(userInfo.id || '')}
                  >
                    <Text style={styles.idText}>ID:{userInfo.id}</Text>
                    <Image
                      source={{ uri: Images.mine.kaixinUserCopyIcon }}
                      style={styles.copyIcon}
                      contentFit="contain"
                    />
                  </TouchableOpacity>
                  {userInfo.phone && (
                    <Text style={styles.phoneText}>手机:{userInfo.phone}</Text>
                  )}
                </View>
              ) : (
                <Text style={styles.loginTip}>点此登录账号</Text>
              )}
            </View>
          </TouchableOpacity>

          {/* 数据统计 */}
          <ImageBackground
            source={{ uri: Images.mine.kaixinUserDataBg }}
            style={styles.dataBox}
            resizeMode="stretch"
          >
            <TouchableOpacity style={styles.dataItem} onPress={() => handleMenuPress('/coupon')}>
              <Text style={styles.dataNum}>{showNumber('couponCount')}</Text>
              <Text style={styles.dataLabel}>优惠券</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.dataItem} onPress={() => handleMenuPress('/store')}>
              <Text style={styles.dataNum}>{showNumber('inventoryCount')}</Text>
              <Text style={styles.dataLabel}>仓库</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.dataItem} onPress={() => handleMenuPress('/magic')}>
              <Text style={styles.dataNum}>{showNumber('magicBalance')}</Text>
              <Text style={styles.dataLabel}>果实</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.dataItem} onPress={() => handleMenuPress('/box-list')}>
              <Text style={styles.dataNum}>{showNumber('treasureBoxCount')}</Text>
              <Text style={styles.dataLabel}>宝箱</Text>
            </TouchableOpacity>
          </ImageBackground>

          {/* 功能入口 */}
          <ImageBackground
            source={{ uri: Images.mine.userSection1Bg }}
            style={styles.funcBox}
            resizeMode="stretch"
          >
            <View style={styles.funcList}>
              {inviteShow && userInfo && (
                <TouchableOpacity style={styles.funcItem} onPress={() => handleMenuPress('/invite')}>
                  <Image source={{ uri: Images.mine.invite }} style={styles.funcIcon} contentFit="contain" />
                  <Text style={styles.funcText}>邀新有礼</Text>
                </TouchableOpacity>
              )}
              {showCredit && (
                <TouchableOpacity style={styles.funcItem} onPress={() => handleMenuPress('/integral')}>
                  <Image source={{ uri: Images.mine.kaixinintegral }} style={styles.funcIcon} contentFit="contain" />
                  <Text style={styles.funcText}>签到领积分</Text>
                </TouchableOpacity>
              )}
              <TouchableOpacity style={styles.funcItem} onPress={() => handleMenuPress('/message')}>
                <Image source={{ uri: Images.mine.message }} style={styles.funcIcon} contentFit="contain" />
                <Text style={styles.funcText}>系统消息</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.funcItem} onPress={() => handleMenuPress('/orders')}>
                <Image source={{ uri: Images.mine.kaixinorder }} style={styles.funcIcon} contentFit="contain" />
                <Text style={styles.funcText}>宝箱订单</Text>
              </TouchableOpacity>
            </View>
          </ImageBackground>

          {/* 订单入口 */}
          <ImageBackground
            source={{ uri: Images.mine.userSection2Bg }}
            style={styles.orderBox}
            resizeMode="stretch"
          >
            <View style={styles.orderList}>
              <TouchableOpacity style={styles.orderItem} onPress={() => handleMenuPress('/orders?tab=1')}>
                <Image source={{ uri: Images.mine.order1 }} style={styles.orderImage} contentFit="contain" />
              </TouchableOpacity>
              <TouchableOpacity style={styles.orderItem} onPress={() => handleMenuPress('/orders?tab=4')}>
                <Image source={{ uri: Images.mine.order2 }} style={styles.orderImage} contentFit="contain" />
              </TouchableOpacity>
            </View>
          </ImageBackground>

          {/* 菜单列表 */}
          <View style={styles.menuSection}>
            <MenuCell onItemPress={handleMenuItemPress} showWallet={showWallet} />
          </View>

          {/* 备案信息 */}
          {filingInfo && filingInfo.state !== 0 && (
            <View style={styles.filingBox}>
              <Text style={styles.filingText}>{filingInfo.data}</Text>
            </View>
          )}

          {/* 底部占位 */}
          <View style={{ height: 120 }} />
        </ScrollView>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  headerBg: {
    position: 'absolute',
    left: 0,
    width: '100%',
    height: 260,
    zIndex: 1,
  },
  scrollView: {
    flex: 1,
    zIndex: 2,
  },
  header: {
    alignItems: 'center',
    paddingBottom: 10,
  },
  title: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    height: 40,
    lineHeight: 40,
  },
  userBox: {
    flexDirection: 'row',
    paddingHorizontal: 22,
    paddingVertical: 8,
    marginHorizontal: 8,
  },
  avatarBox: {
    width: 64,
    height: 64,
    borderRadius: 32,
    overflow: 'hidden',
    marginRight: 21,
  },
  avatar: {
    width: '100%',
    height: '100%',
  },
  userInfo: {
    flex: 1,
    justifyContent: 'center',
  },
  nicknameRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  nickname: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '700',
  },
  editIcon: {
    width: 67,
    height: 23,
  },
  idRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  idItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 22,
  },
  idText: {
    color: '#fff',
    fontSize: 11,
    fontWeight: 'bold',
  },
  copyIcon: {
    width: 11,
    height: 11,
    marginLeft: 5,
  },
  phoneText: {
    color: '#fff',
    fontSize: 11,
    fontWeight: 'bold',
  },
  loginTip: {
    color: '#fff',
    fontSize: 12,
  },
  dataBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 360,
    height: 57,
    marginHorizontal: 'auto',
    paddingHorizontal: 11,
    alignSelf: 'center',
  },
  dataItem: {
    width: '25%',
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 10,
  },
  dataNum: {
    color: '#000',
    fontSize: 16,
    fontWeight: 'bold',
  },
  dataLabel: {
    color: '#934800',
    fontSize: 12,
  },
  funcBox: {
    height: 115,
    marginHorizontal: 0,
    paddingTop: 20,
    paddingHorizontal: 10,
  },
  funcList: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  funcItem: {
    alignItems: 'center',
  },
  funcIcon: {
    width: 59,
    height: 57,
  },
  funcText: {
    color: '#000',
    fontSize: 12,
  },
  orderBox: {
    marginHorizontal: 8,
    paddingTop: 20,
    paddingHorizontal: 16,
    paddingBottom: 25,
  },
  orderList: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  orderItem: {
    width: 161,
  },
  orderImage: {
    width: 161,
    height: 75,
  },
  filingBox: {
    alignItems: 'center',
    marginTop: 20,
    paddingHorizontal: 20,
  },
  filingText: {
    color: '#fff',
    fontSize: 14,
    textAlign: 'center',
  },
  menuSection: {
    backgroundColor: '#fff',
    marginHorizontal: 8,
    marginTop: 10,
    borderRadius: 8,
    overflow: 'hidden',
  },
});
