import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../widgets/admin_drawer.dart';
import '../../widgets/backoffice_ui.dart';
import 'admin_doctors_page.dart';
import 'admin_patients_page.dart';

final adminPageProvider = NotifierProvider<AdminPageNotifier, String>(
  AdminPageNotifier.new,
);

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

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

  @override
  ConsumerState<AdminHomePage> createState() => _AdminHomePageState();
}

class _AdminHomePageState extends ConsumerState<AdminHomePage> {
  final List<Widget?> _pages = [const AdminDoctorsPage(), null];

  @override
  Widget build(BuildContext context) {
    final page = ref.watch(adminPageProvider);
    final pageIndex = page == 'patients' ? 1 : 0;
    _pages[pageIndex] ??= const AdminPatientsPage();

    return PopScope(
      canPop: page == 'doctors',
      onPopInvokedWithResult: (didPop, _) {
        if (!didPop) ref.read(adminPageProvider.notifier).set('doctors');
      },
      child: Scaffold(
        backgroundColor: AppColors.pageGrey,
        drawerEnableOpenDragGesture: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          title: Text(
            page == 'patients' ? '患者管理' : '医生管理',
            style: TextStyle(color: AppColors.textPrimary),
          ),
          iconTheme: const IconThemeData(color: AppColors.textPrimary),
        ),
        drawer: const AdminDrawer(),
        body: BackofficeSurface(
          child: IndexedStack(
            index: pageIndex,
            children: _pages
                .map((page) => page ?? const SizedBox.shrink())
                .toList(growable: false),
          ),
        ),
      ),
    );
  }
}
