import {useEffect, useRef, useState} from 'react'
import {PullToRefresh} from '@nutui/nutui-react-taro'
import UserCard from "./components/UserCard";
import UserFooter from "./components/UserFooter";
import {View} from '@tarojs/components';
import './user.scss'
import {useThemeStyles} from "@/hooks/useTheme";
import UserGrid from "@/pages/user/components/UserGrid";
import { useDidShow } from '@tarojs/taro'

function User() {

  const userCardRef = useRef<any>()
  const themeStyles = useThemeStyles();
  // 仅覆盖个人中心页顶部背景为红色（不影响全局主题）
  const pagePrimaryBackground = {
    ...themeStyles.primaryBackground,
    background: '#cf1313'
  }
  // TabBar 页在小程序里通常不会销毁；从“注册/申请”页返回时需要触发子组件重新初始化/拉取最新状态。
  const [dealerViewKey, setDealerViewKey] = useState(0)
  console.log(dealerViewKey)
  // 下拉刷新处理
  const handleRefresh = async () => {
    if (userCardRef.current?.handleRefresh) {
      await userCardRef.current.handleRefresh()
    }
    setDealerViewKey(v => v + 1)
  }

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

  // 每次进入/切回个人中心都刷新一次统计（包含水票数量）
  useDidShow(() => {
    userCardRef.current?.reloadStats?.()
    // 个人资料（头像/昵称）可能在其它页面被修改，这里确保返回时立刻刷新
    userCardRef.current?.reloadUserInfo?.()
    setDealerViewKey(v => v + 1)
  })

  return (
    <PullToRefresh
      onRefresh={handleRefresh}
      headHeight={60}
    >
      {/* 装饰性背景 */}
      <View className={'h-64 w-full fixed top-0 z-0'} style={pagePrimaryBackground}>
        {/* 装饰性背景元素 - 小程序兼容版本 */}
        <View className="absolute w-32 h-32 rounded-full" style={{
          backgroundColor: 'rgba(255, 255, 255, 0.1)',
          top: '-16px',
          right: '-16px'
        }}></View>
        <View className="absolute w-24 h-24 rounded-full" style={{
          backgroundColor: 'rgba(255, 255, 255, 0.08)',
          bottom: '-12px',
          left: '-12px'
        }}></View>
        <View className="absolute w-16 h-16 rounded-full" style={{
          backgroundColor: 'rgba(255, 255, 255, 0.05)',
          top: '60px',
          left: '120px'
        }}></View>
      </View>
      <UserCard ref={userCardRef}/>
      <UserGrid/>
      <UserFooter/>
    </PullToRefresh>
  )
}

export default User
