import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:remixicon/remixicon.dart';

import '../page/home/home_page.dart';
import '../page/profile/my/my_page.dart';
import '../page/record/list/record_list_page.dart';
import '../providers/user_store.dart';
import '../router/config/route_paths.dart';
import 'tabbar.dart';

class LayoutPage extends StatefulWidget {
  const LayoutPage({super.key});

  @override
  State<LayoutPage> createState() => _LayoutPageState();
}

class _LayoutPageState extends State<LayoutPage> {
  ///分页
  final PageController _pageController = PageController(initialPage: 0);

  int get currentPage {
    if (!_pageController.hasClients) return 0; // 没 attach 直接 0
    return _pageController.page?.round() ?? 0;
  }

  //TabBar列表
  final List<PageItem> _pages = [
    PageItem(
      name: "Home",
      icon: RemixIcons.home_2_line,
      page: HomePage(),
    ),
    PageItem(
      name: "Record",
      icon: RemixIcons.history_line,
      page: RecordListPage(),
    ),
    PageItem(
      name: "My",
      icon: RemixIcons.book_open_line,
      page: MyPage(),
    ),
  ];

  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init() async {
    UserStore userStore = context.read<UserStore>();
    await userStore.init();
    print(userStore.profile.toString());
    if (userStore.profile.qStatus != 1) {
      showCupertinoDialog(
        context: context,
        builder: (_) => CupertinoAlertDialog(
          title: Text("Complete Your Profile"),
          content: Text("Let’s get to know you better! Please take a quick survey to personalize your experience."),
          actions: [
            CupertinoDialogAction(
              child: Text("Take Survey"),
              onPressed: () {
                context.pop();
                _goEditProfile();
              },
            ),
          ],
        ),
      );
    }
  }

  void _goEditProfile() async {
    var isUpload = await context.push(RoutePaths.myEdit);
    if (isUpload == true) {
      UserStore userStore = context.read<UserStore>();
      userStore.init();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: _pageController,
        physics: const NeverScrollableScrollPhysics(),
        children: _pages.map((item) => item.page).toList(),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentPage,
        onTap: (index) {
          _pageController.jumpToPage(index);
          setState(() {});
        },
        items: _pages.map((item) {
          return BottomNavigationBarItem(
            icon: Icon(item.icon),
            label: item.name,
          );
        }).toList(),
        showSelectedLabels: false,
        showUnselectedLabels: false,
      ),
    );
  }
}
