import React, { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useGlobalState } from '@/store/global';
import { GeneralNavbar } from '@/components';
import './index.scss';

interface EmptyStateProps {
  onGoToOtherGames?: () => void;
  onGoToHome?: () => void;
}

const EmptyState: React.FC<EmptyStateProps> = ({ onGoToOtherGames, onGoToHome }) => {
  const { statusNavbarHeightInfo } = useGlobalState() || {};
  const { totalHeight = 98 } = statusNavbarHeightInfo || {};
  const [countdown, setCountdown] = useState(5);

  // 倒计时自动返回
  useEffect(() => {
    if (countdown <= 0) {
      handle_go_to_home();
      return;
    }

    const timer = setTimeout(() => {
      setCountdown(countdown - 1);
    }, 1000);

    return () => clearTimeout(timer);
  }, [countdown]);

  // 跳转到其他球局
  const handle_go_to_other_games = () => {
    if (onGoToOtherGames) {
      onGoToOtherGames();
    } else {
      Taro.switchTab({
        url: '/main_pages/index',
      });
    }
  };

  // 返回首页
  const handle_go_to_home = () => {
    if (onGoToHome) {
      onGoToHome();
    } else {
      const pages = Taro.getCurrentPages();
      if (pages.length <= 1) {
        Taro.switchTab({
          url: '/main_pages/index',
        });
      } else {
        Taro.navigateBack();
      }
    }
  };

  return (
    <View className="empty_state_page" style={{ paddingTop: `${totalHeight}px` }}>
      <GeneralNavbar title="" showBack={true} />

      <View className="empty_state_page__content">
        {/* 背景图片 */}
        <View className="empty_state_page__bg_image" />

        {/* 提示文字 */}
        <View className="empty_state_page__tip">
          <Text className="empty_state_page__tip_text">
            页面将在 {countdown}s 后自动返回球局首页
          </Text>
        </View>

        {/* 按钮区域 */}
        <View className="empty_state_page__buttons">
          <View
            className="empty_state_page__button empty_state_page__button--primary"
            onClick={handle_go_to_other_games}
          >
            <Text className="empty_state_page__button_text">去看看其他球局</Text>
          </View>
          <View
            className="empty_state_page__button empty_state_page__button--secondary"
            onClick={handle_go_to_home}
          >
            <Text className="empty_state_page__button_text">返回首页</Text>
          </View>
        </View>
      </View>
    </View>
  );
};

export default EmptyState;

