import Header from './Header';
import BestSellers from './BestSellers';
import Taro from '@tarojs/taro';
import {useShareAppMessage, useShareTimeline} from "@tarojs/taro"
import {useEffect, useState} from "react";
import {Sticky} from '@nutui/nutui-react-taro'
import { useShopInfo } from '@/hooks/useShopInfo';
import { useUser } from '@/hooks/useUser';
import Menu from "./Menu";
import Banner from "./Banner";
import './index.scss'

const Home = () => {
  const [stickyStatus, setStickyStatus] = useState(false);

  // 使用新的hooks
  const {
    shopInfo,
    loading: shopLoading,
    error: shopError,
    getWebsiteName,
    getWebsiteLogo,
    refreshShopInfo
  } = useShopInfo();

  const {
    user,
    isLoggedIn,
    loading: userLoading
  } = useUser();

  const onSticky = (args: any) => {
    setStickyStatus(args[0].isFixed);
  };

  const showAuthModal = () => {
    Taro.showModal({
      title: '授权提示',
      content: '需要获取您的用户信息',
      confirmText: '去授权',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，打开授权设置页面
          Taro.openSetting({
            success: (settingRes) => {
              if (settingRes.authSetting['scope.userInfo']) {
                console.log('用户已授权');
              } else {
                console.log('用户拒绝授权');
              }
            }
          });
        }
      }
    });
  };

  // 分享给好友
  useShareAppMessage(() => {
    return {
      title: `${getWebsiteName()} - 精选商城`,
      path: '/pages/index/index',
      imageUrl: getWebsiteLogo(),
      success: function (res: any) {
        console.log('分享成功', res);
        Taro.showToast({
          title: '分享成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: function (res: any) {
        console.log('分享失败', res);
        Taro.showToast({
          title: '分享失败',
          icon: 'none',
          duration: 2000
        });
      }
    };
  });

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: `${getWebsiteName()} - 精选商城`,
      imageUrl: getWebsiteLogo(),
      success: function (res: any) {
        console.log('分享到朋友圈成功', res);
      },
      fail: function (res: any) {
        console.log('分享到朋友圈失败', res);
      }
    };
  });

  useEffect(() => {
    // 设置页面标题
    if (shopInfo?.appName) {
      Taro.setNavigationBarTitle({
        title: shopInfo.appName
      });
    }
  }, [shopInfo]);

  useEffect(() => {
    // 检查用户授权状态
    Taro.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          console.log('用户已经授权过，可以直接获取用户信息');
        } else {
          console.log('用户未授权，需要弹出授权窗口');
          showAuthModal();
        }
      }
    });

    // 获取用户基本信息（头像、昵称等）
    Taro.getUserInfo({
      success: (res) => {
        const avatar = res.userInfo.avatarUrl;
        console.log('用户头像:', avatar);
      },
      fail: (err) => {
        console.log('获取用户信息失败:', err);
      }
    });
  }, []);

  // 处理错误状态
  if (shopError) {
    return (
      <div style={{padding: '20px', textAlign: 'center'}}>
        <div>加载商店信息失败: {shopError}</div>
        <button
          onClick={refreshShopInfo}
          style={{marginTop: '10px', padding: '10px 20px'}}
        >
          重试
        </button>
      </div>
    );
  }

  // 显示加载状态
  if (shopLoading) {
    return (
      <div style={{padding: '20px', textAlign: 'center'}}>
        <div>加载中...</div>
      </div>
    );
  }

  return (
    <>
      <Sticky threshold={0} onChange={(args) => onSticky(args)}>
        <Header stickyStatus={stickyStatus}/>
      </Sticky>
      <div className={'flex flex-col mt-12'}>
        <Menu/>
        <Banner/>
        <BestSellers/>

        {/* 调试信息面板 - 仅在开发环境显示 */}
        {process.env.NODE_ENV === 'development' && (
          <div style={{
            position: 'fixed',
            bottom: '10px',
            right: '10px',
            background: 'rgba(0,0,0,0.8)',
            color: 'white',
            padding: '10px',
            borderRadius: '5px',
            fontSize: '12px',
            maxWidth: '200px'
          }}>
            <div>商店: {getWebsiteName()}</div>
            <div>用户: {isLoggedIn ? (user?.nickname || '已登录') : '未登录'}</div>
            <div>加载: {userLoading ? '用户加载中' : '已完成'}</div>
          </div>
        )}
      </div>
    </>
  )
}

export default Home;
