import { useEffect, useState } from 'react';
import { useAppStore, getStatusColor } from '../stores/appStore';
import styles from './StartupCheck.module.css';

interface StartupCheckProps {
  onComplete: () => void;
}

export default function StartupCheck({ onComplete }: StartupCheckProps) {
  const { environment, checkAllServices, appReady } = useAppStore();
  const [showDetails, setShowDetails] = useState(false);

  useEffect(() => {
    const runCheck = async () => {
      await checkAllServices();
    };
    runCheck();
  }, [checkAllServices]);

  useEffect(() => {
    // 检测完成后自动进入主界面（成功或失败都进入）
    if (appReady === 'ready' || appReady === 'error') {
      const timer = setTimeout(() => {
        onComplete();
      }, 1500); // 1.5秒后自动进入
      return () => clearTimeout(timer);
    }
  }, [appReady, onComplete]);

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'connected':
        return '✅';
      case 'checking':
        return '🔄';
      case 'error':
        return '❌';
      default:
        return '⏳';
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.card}>
        {/* Logo */}
        <div className={styles.logo}>
          <span className={styles.logoIcon}>🍈</span>
          <h1 className={styles.title}>绿积分共管账户服务</h1>
          <p className={styles.subtitle}>榴莲皇后 · 分布式多方共管钱包</p>
        </div>

        {/* 状态检测 */}
        <div className={styles.checkList}>
          <div className={styles.checkItem}>
            <span className={styles.checkIcon}>{getStatusIcon(environment.database.status)}</span>
            <span className={styles.checkLabel}>本地数据库</span>
            <span
              className={styles.checkStatus}
              style={{ color: getStatusColor(environment.database.status) }}
            >
              {environment.database.status === 'connected'
                ? '正常'
                : environment.database.status === 'checking'
                ? '检测中...'
                : environment.database.status === 'error'
                ? '异常'
                : '等待检测'}
            </span>
          </div>

          <div className={styles.checkItem}>
            <span className={styles.checkIcon}>{getStatusIcon(environment.messageRouter.status)}</span>
            <span className={styles.checkLabel}>消息路由服务</span>
            <span
              className={styles.checkStatus}
              style={{ color: getStatusColor(environment.messageRouter.status) }}
            >
              {environment.messageRouter.status === 'connected'
                ? '已连接'
                : environment.messageRouter.status === 'checking'
                ? '检测中...'
                : environment.messageRouter.status === 'error'
                ? '连接失败'
                : '等待检测'}
            </span>
          </div>

          <div className={styles.checkItem}>
            <span className={styles.checkIcon}>{getStatusIcon(environment.kavaApi.status)}</span>
            <span className={styles.checkLabel}>Kava 区块链 API</span>
            <span
              className={styles.checkStatus}
              style={{ color: getStatusColor(environment.kavaApi.status) }}
            >
              {environment.kavaApi.status === 'connected'
                ? '已连接'
                : environment.kavaApi.status === 'checking'
                ? '检测中...'
                : environment.kavaApi.status === 'error'
                ? '连接失败'
                : '等待检测'}
            </span>
          </div>
        </div>

        {/* 总体状态 */}
        <div className={styles.summary}>
          {appReady === 'initializing' && (
            <>
              <div className={styles.spinner} />
              <span>正在初始化环境...</span>
            </>
          )}
          {appReady === 'ready' && (
            <>
              <span className={styles.successIcon}>✅</span>
              <span>环境检测完成，即将进入主界面</span>
            </>
          )}
          {appReady === 'error' && (
            <>
              <span className={styles.warningIcon}>⚠️</span>
              <span>部分服务异常，但仍可使用基本功能</span>
            </>
          )}
        </div>

        {/* 详情按钮 */}
        {(environment.messageRouter.message || environment.kavaApi.message) && (
          <button
            className={styles.detailsButton}
            onClick={() => setShowDetails(!showDetails)}
          >
            {showDetails ? '隐藏详情' : '查看详情'}
          </button>
        )}

        {/* 详细信息 */}
        {showDetails && (
          <div className={styles.details}>
            {environment.messageRouter.message && (
              <div className={styles.detailRow}>
                <span className={styles.detailLabel}>消息路由:</span>
                <span className={styles.detailValue}>{environment.messageRouter.message}</span>
              </div>
            )}
            {environment.kavaApi.message && (
              <div className={styles.detailRow}>
                <span className={styles.detailLabel}>Kava API:</span>
                <span className={styles.detailValue}>{environment.kavaApi.message}</span>
              </div>
            )}
            {environment.database.message && (
              <div className={styles.detailRow}>
                <span className={styles.detailLabel}>本地存储:</span>
                <span className={styles.detailValue}>{environment.database.message}</span>
              </div>
            )}
          </div>
        )}

        {/* 手动进入按钮 */}
        {(appReady === 'ready' || appReady === 'error') && (
          <button className={styles.enterButton} onClick={onComplete}>
            进入应用
          </button>
        )}
      </div>
    </div>
  );
}
