import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/localization/app_localizations.dart';
import '../../../core/theme/app_theme.dart';
import '../../../shared/widgets/common_button.dart';
import '../providers/steps_provider.dart';
import '../widgets/step_list.dart';
import '../widgets/step_form.dart';
import '../../home/widgets/status_bar.dart';
import '../../device/providers/run_state_provider.dart';
import '../../programs/providers/programs_provider.dart';

/// 程序详情页面
/// 布局:顶部状态栏(含导航tab) + 子工具栏(返回/程序名/保存) + 左侧步骤列表 + 右侧参数表单
class ProgramDetailPage extends ConsumerStatefulWidget {
  final String programId;

  const ProgramDetailPage({super.key, required this.programId});

  @override
  ConsumerState<ProgramDetailPage> createState() => _ProgramDetailPageState();
}

class _ProgramDetailPageState extends ConsumerState<ProgramDetailPage> {
  late int _programIdInt;

  @override
  void initState() {
    super.initState();
    _programIdInt = int.tryParse(widget.programId) ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    final programsState = ref.watch(programsProvider);
    final program = programsState.programs.where((p) => p.id == _programIdInt).firstOrNull;
    final stepsState = ref.watch(stepsProvider(_programIdInt));
    final runState = ref.watch(runStateProvider);

    // 详情页从程序管理进入,高亮"程序管理"tab(index=1)
    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.backgroundColor,
        child: Column(
          children: [
            // 顶部状态栏(含导航tab),tab点击跳回首页对应 tab
            StatusBar(
              isRunning: runState.status == RunStatus.running,
              tabs: tabs,
              currentTabIndex: 1,
              onTabChanged: (index) => context.go('/?tab=$index'),
            ),

            // 子工具栏:返回按钮 + 程序名 + 保存按钮
            _buildSubToolbar(context, l10n, program?.name),

            // 主内容区域
            Expanded(
              child: stepsState.isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : Row(
                      children: [
                        // 左侧：步骤列表
                        SizedBox(
                          width: 400,
                          child: StepList(
                            programId: _programIdInt,
                            steps: stepsState.steps,
                            selectedStepId: stepsState.selectedStepId,
                            onStepSelected: (stepId) {
                              ref.read(stepsProvider(_programIdInt).notifier).selectStep(stepId);
                            },
                            onAddStep: () => _showAddStepDialog(context, ref),
                            onReorder: (oldIndex, newIndex) {
                              ref.read(stepsProvider(_programIdInt).notifier).reorderSteps(oldIndex, newIndex);
                            },
                            onDeleteSteps: (stepIds) {
                              ref.read(stepsProvider(_programIdInt).notifier).deleteSteps(stepIds);
                            },
                          ),
                        ),

                        // 分隔线
                        Container(
                          width: 1,
                          color: AppTheme.idleColor.withValues(alpha: 0.3),
                        ),

                        // 右侧：步骤参数表单
                        Expanded(
                          child: stepsState.selectedStep != null
                              ? StepForm(
                                  programId: _programIdInt,
                                  step: stepsState.selectedStep!,
                                  onSave: (step) async {
                                    final success = await ref
                                        .read(stepsProvider(_programIdInt).notifier)
                                        .updateStep(step);
                                    if (success) {
                                      ScaffoldMessenger.of(context).showSnackBar(
                                        SnackBar(
                                          content: Text(l10n?.stepUpdated ?? '步骤已更新'),
                                          backgroundColor: AppTheme.successColor,
                                        ),
                                      );
                                    }
                                  },
                                )
                              : Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.edit_note,
                                        size: 64,
                                        color: AppTheme.idleColor,
                                      ),
                                      const SizedBox(height: 16),
                                      Text(
                                        l10n?.selectStepFirst ?? '请选择或添加步骤',
                                        style: TextStyle(
                                          color: AppTheme.textSecondary,
                                          fontSize: 16,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                        ),
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }

  /// 子工具栏:返回按钮 + 程序名 + 保存按钮
  /// 位于状态栏下方,提供详情页特有的操作入口
  Widget _buildSubToolbar(BuildContext context, AppLocalizations? l10n, String? programName) {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 24),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.06),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back),
            tooltip: l10n?.back ?? '返回',
            onPressed: () => context.go('/?tab=1'),
          ),
          const SizedBox(width: 8),
          Text(
            programName ?? (l10n?.detail ?? '程序详情'),
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: AppTheme.textHeading,
            ),
          ),
          const Spacer(),
          CommonButton(
            text: l10n?.save ?? '保存',
            icon: Icons.save,
            type: ButtonType.primary,
            onPressed: () {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(l10n?.saved ?? '已保存'),
                  backgroundColor: AppTheme.successColor,
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  /// 显示添加步骤对话框
  void _showAddStepDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: Container(
          width: 600,
          padding: const EdgeInsets.all(24),
          child: StepForm(
            programId: _programIdInt,
            isNew: true,
            onSave: (step) async {
              final success = await ref
                  .read(stepsProvider(_programIdInt).notifier)
                  .addStep(step);
              if (success) {
                Navigator.of(context).pop();
              }
            },
          ),
        ),
      ),
    );
  }
}