import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../widgets/doctor_drawer.dart';
import '../../widgets/backoffice_ui.dart';
import 'doctor_dashboard_page.dart';
import 'doctor_patients_page.dart';
import 'doctor_consultations_page.dart';
import 'doctor_reports_page.dart';
import 'doctor_followups_page.dart';

class DoctorHomePage extends ConsumerStatefulWidget {
  const DoctorHomePage({super.key});

  @override
  ConsumerState<DoctorHomePage> createState() => _DoctorHomePageState();
}

class _DoctorHomePageState extends ConsumerState<DoctorHomePage> {
  final List<Widget?> _pages = [
    const DoctorDashboardPage(),
    null,
    null,
    null,
    null,
  ];

  Widget _createPage(int index) => switch (index) {
    1 => const DoctorPatientsPage(),
    2 => const DoctorConsultationsPage(),
    3 => const DoctorReportsPage(),
    4 => const DoctorFollowupsPage(),
    _ => const DoctorDashboardPage(),
  };

  @override
  Widget build(BuildContext context) {
    final page = ref.watch(doctorPageProvider);
    final pageIndex = switch (page) {
      'patients' => 1,
      'consultations' => 2,
      'reports' => 3,
      'followups' => 4,
      _ => 0,
    };
    _pages[pageIndex] ??= _createPage(pageIndex);

    return PopScope(
      canPop: page == 'dashboard',
      onPopInvokedWithResult: (didPop, _) {
        if (!didPop) ref.read(doctorPageProvider.notifier).set('dashboard');
      },
      child: Scaffold(
        backgroundColor: AppColors.background,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          surfaceTintColor: Colors.transparent,
          title: Text(
            _titleFor(page),
            style: const TextStyle(color: AppColors.textPrimary),
          ),
          leading: Builder(
            builder: (ctx) => IconButton(
              icon: const Icon(Icons.menu, color: AppColors.textPrimary),
              onPressed: () => Scaffold.of(ctx).openDrawer(),
            ),
          ),
        ),
        drawer: const DoctorDrawer(),
        drawerEnableOpenDragGesture: true,
        body: BackofficeSurface(
          child: IndexedStack(
            index: pageIndex,
            children: _pages
                .map((page) => page ?? const SizedBox.shrink())
                .toList(growable: false),
          ),
        ),
      ),
    );
  }

  String _titleFor(String page) => switch (page) {
    'dashboard' => '工作台',
    'patients' => '患者管理',
    'consultations' => '问诊列表',
    'reports' => '报告审核',
    'followups' => '复查随访',
    _ => '工作台',
  };
}

final doctorPageProvider = NotifierProvider<DoctorPageNotifier, String>(
  DoctorPageNotifier.new,
);

class DoctorPageNotifier extends Notifier<String> {
  @override
  String build() => 'dashboard';
  void set(String page) => state = page;
}
