import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:vbvs_app/pages/common/bezier_bottom_navigation_bar.dart';
import 'package:vbvs_app/pages/mh_page/MattressControl.dart';
import 'package:vbvs_app/pages/mh_page/homepage/mht_sleep_report_page.dart';
import 'package:vbvs_app/pages/mh_page/homepage/new_Home_page.dart';
import 'package:vbvs_app/pages/mh_page/new_mine_page.dart';
import 'package:vbvs_app/pages/mh_page/test/WebviewTestModel.dart';

class MainPageBBottomChange extends StatefulWidget {
  // 全局 key，用于静态访问 _HomePageState
  static final GlobalKey<_HomePageState> globalKey =
      GlobalKey<_HomePageState>();

  MainPageBBottomChange({Key? key}) : super(key: globalKey);

  // 静态方法：外部调用，跳转 tab
  static void jumpTo(int index) {
    final state = globalKey.currentState;
    if (state != null) {
      state.switchTab(index);
    }
  }

  static int? getCurrentIndex() {
    final state = globalKey.currentState;
    return state?.selectedIndex;
  }

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<MainPageBBottomChange>
    with SingleTickerProviderStateMixin {
  int selectedIndex = 0;
  late AnimationController _controller;
  late Animation<double> _positionAnimation;
  double currentPosition = 0.0;

  final List<String> titles = ['首页', '报告', '控制', '我的'];
  final List<String> path = [
    "assets/images/bar_home.svg",
    "assets/images/bar_heart.svg",
    "assets/images/bar_control.svg",
    "assets/images/bar_mine.svg"
  ];

  final List<Widget> pages = [
    NewHomePage(),
    // PeopleInfoPage(),
    // Text('报告'),
    // RegisterPage(),
    // ShareDeviceWidget(),
    // DeviceListPage(),
    MhtSleepReportPage(),
    // FindPasswordPage(),
    // Smys(),
    MattressControlPage(),
    NewMinePage()
  ];
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 300));
    currentPosition = selectedIndex.toDouble();
    _positionAnimation = Tween<double>(
            begin: currentPosition, end: currentPosition)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut))
      ..addListener(() {
        setState(() {}); // trigger rebuild for CustomPainter
      });
  }

  void _onTabTapped(int index) {
    setState(() {
      dealWebSource(index);
      final begin = currentPosition;
      final end = index.toDouble();
      _positionAnimation = Tween<double>(begin: begin, end: end).animate(
        CurvedAnimation(parent: _controller, curve: Curves.easeOut),
      )..addListener(() {
          setState(() {});
        });
      _controller.forward(from: 0.0);
      currentPosition = end;
      selectedIndex = index;
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget _buildPageContent() {
    return Center(child: Text('页面 ${titles[selectedIndex]}'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF011C33),
      body: IndexedStack(
        index: selectedIndex,
        children: pages,
      ),
      bottomNavigationBar: BezierBottomNavigationBar(
        selectedIndex: selectedIndex,
        animatedPosition: _positionAnimation.value,
        onTap: _onTabTapped,
        path: path,
        titles: titles,
      ),
    );
  }

  void switchTab(int index) {
    final begin = currentPosition;
    final end = index.toDouble();

    _positionAnimation = Tween<double>(begin: begin, end: end).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeOut),
    )..addListener(() {
        setState(() {});
      });

    _controller.forward(from: 0.0);
    currentPosition = end;

    setState(() {
      selectedIndex = index;
    });
  }

  Future<void> dealWebSource(int index) async {
    WebviewTestController webviewTestController = Get.find();
    if (index == 2) {
      await webviewTestController.web.jsbridge?.dart.pageActive(true);
    } else {
      await webviewTestController.web.jsbridge?.dart.pageInActive();
    }
  }
}
