import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnoteapp/components/cell.dart';
import 'package:vnoteapp/consts/styles.dart';
import 'package:vnoteapp/routes/transition.dart';

import 'controller.dart';
import 'defines.dart';

part 'nav_view.dart';
part 'side_bar.dart';

class VSideNavView extends StatefulWidget {
  /// 导航Id
  ///
  /// 设为`null`时，不使用路由模式，通过`VSideNavMenuItem.pageBuilder`构建页面
  final int? navId;

  /// 菜单项集合
  final List<VSideNavMenuItem> items;

  final VSideNavViewController? controller;

  final int leftFlex;
  final int rightFlex;

  const VSideNavView({
    super.key,
    this.navId,
    required this.items,
    this.controller,
    this.leftFlex = 1,
    this.rightFlex = 2,
  });

  @override
  State<StatefulWidget> createState() => _VSideNavViewState();
}

class _VSideNavViewState extends State<VSideNavView> {
  late final VSideNavViewController controller;
  @override
  void initState() {
    controller = widget.controller ?? VSideNavViewController();
    _init();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final sideView = _SideBar(
      controller: controller,
      items: widget.items,
      navId: widget.navId,
    );
    final navView = _NavView(
      controller: controller,
      items: widget.items,
      navId: widget.navId,
    );

    return Container(
      child: Row(
        children: [
          Expanded(
            flex: widget.leftFlex,
            child: sideView,
          ),
          const VerticalDivider(width: 1),
          Expanded(
            flex: widget.rightFlex,
            child: navView,
          ),
        ],
      ),
    );
  }

  void _init() {
    if (widget.navId != null) {
      _initRoute();
    } else {
      _initFirstPage();
    }
  }

  void _initFirstPage() {
    final firstPageItem =
        widget.items.firstWhereOrNull((e) => e.pageBuilder != null);
    final builder = firstPageItem?.pageBuilder;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      controller.pageChangedEvent.emit(this, builder);
    });
  }

  void _initRoute() {
    final firstRouteItem =
        widget.items.firstWhereOrNull((e) => e.route != null);

    final firstRoute = firstRouteItem?.route;
    controller.routeChangedEvent.emit(this, firstRoute?.name);
  }
}
