import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/database/database_service.dart';
import '../../../core/localization/app_localizations.dart';
import '../../../core/theme/app_theme.dart';
import '../../device/providers/run_state_provider.dart';
import '../../programs/pages/programs_page.dart';
import '../../settings/pages/settings_page.dart';
import '../widgets/status_bar.dart';
import '../widgets/program_list.dart';
import '../widgets/running_control_panel.dart';
import '../widgets/run_status_monitor.dart';

/// 首页 - 设备控制面板 (暗色工业风格)
/// 布局：状态栏(含标签导航) + 内容区（设备控制/程序管理/系统设置）
///
/// [initialTab] 用于从子页面(如程序详情页)跳转回首页时指定要显示的 tab
class HomePage extends ConsumerStatefulWidget {
  final int initialTab;

  const HomePage({super.key, this.initialTab = 0});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage>
    with SingleTickerProviderStateMixin {
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialTab.clamp(0, 2);
    DatabaseService.instance.initTestData();
  }

  @override
  Widget build(BuildContext context) {
    final runState = ref.watch(runStateProvider);
    final l10n = AppLocalizations.of(context);

    // 监听运行完成状态，自动跳转
    ref.listen<RunState>(runStateProvider, (prev, next) {
      if (prev?.status != RunStatus.completed && next.status == RunStatus.completed) {
        // 仅首页才自动跳转
        if (_currentIndex == 0) {
          context.push('/complete');
        }
      }
    });

    final tabs = <StatusBarTab>[
      StatusBarTab(icon: Icons.dashboard, label: l10n?.deviceControl ?? '设备控制'),
      StatusBarTab(icon: Icons.list_alt, label: l10n?.programs ?? '程序管理'),
      StatusBarTab(icon: Icons.settings, label: l10n?.settings ?? '系统设置'),
    ];

    return Scaffold(
      body: Container(
        color: AppTheme.bgDeep,
        child: Column(
          children: [
            // 状态栏(内嵌标签导航)
            StatusBar(
              isRunning: runState.status == RunStatus.running,
              tabs: tabs,
              currentTabIndex: _currentIndex,
              onTabChanged: (index) => setState(() => _currentIndex = index),
            ),

            // 内容区
            Expanded(
              child: IndexedStack(
                index: _currentIndex,
                children: [
                  _buildDeviceControlPage(runState),
                  const ProgramsPage(),
                  const SettingsPage(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 设备控制页面内容
  Widget _buildDeviceControlPage(RunState runState) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Row(
        children: [
          // 左侧：程序列表（运行时锁定），占 2/5 宽度
          Expanded(
            flex: 2,
            child: Opacity(
              opacity: runState.status == RunStatus.idle ? 1.0 : 0.6,
              child: IgnorePointer(
                ignoring: runState.status != RunStatus.idle,
                child: const ProgramList(),
              ),
            ),
          ),
          const SizedBox(width: 20),
          // 右侧：运行控制区域，占 3/5 宽度
          Expanded(
            flex: 3,
            child: Column(
              children: [
                const RunningControlPanel(),
                if (runState.status != RunStatus.idle) ...[
                  const SizedBox(height: 16),
                  const Expanded(child: RunStatusMonitor()),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }
}
