import 'package:design/design.dart';
import 'package:guru_widgets/button/single_tap_widget.dart';
import 'package:guru_widgets/common/divider.dart';
import 'package:guru_widgets/common/flexible_container.dart';
import 'package:guru_widgets/theme/guru_theme.dart';

part 'guru_navigation_bar.g.dart';

@DesignSpec(width: 750, height: 49, specMode: SpecMode.nested)
abstract class GuruNavigationBarDesignSpec implements BasicDesignSpec {
  @SpecHeight(98)
  double get navigationBarHeight;

  @SpecWidth(53)
  double get navigationBarSpacing2;

  @SpecWidth(34)
  double get navigationBarSpacing3;

  @SpecWidth(19)
  double get navigationBarSpacing4;

  @SpecWidth(17)
  double get navigationBarSpacing5;

  @SpecFontSize(20)
  double get navigationBarLabelFontSize;

  @SpecHeight(56)
  double get navigationBarLabelIconSize;

  @SpecWidth(140)
  double get navigationBarItemWidth;

  @SpecHeight(80)
  double get navigationBarIconSize;

  static GuruNavigationBarDesignSpec create(Size size,
          {Offset offset = Offset.zero}) =>
      _GuruNavigationBarDesignSpec.from(size, offset: offset);
}

class GuruNavigationBarItem {
  /// Title is tab text
  final String? label;

  /// Icon is a image instead of title
  final String icon;

  final String activeIcon;

  GuruNavigationBarItem(
      {this.label, required this.icon, required this.activeIcon});
}

/// Guru Tab Bar (Tabs 标签页组件).
/// Guru Tab Bar provides a tabbar where each tab indicator is a toggle button.
/// It allows you to create interactive and compliant tab bars for your Flutter applications
///
/// {@tool dartpad}
/// This is an example to create [GuruTabBar]
///
/// ** See code in examples/lib/pages/tabbar/tarbar_View.dart **
/// {@end-tool}

class GuruNavigationBar extends StatefulWidget {
  /// currentIndex
  /// [GuruNavigationBar] tab index initially selected. The default value is 0.
  /// [GuruNavigationBar] 初始选中的标签的index， 默认为0。

  final int currentIndex;

  /// Items
  /// [GuruNavigationBar] tabs's configure, Up to four items, item is [GuruTabBarItem].
  /// [GuruNavigationBar] 配置选项卡内容，最多四个标签项, 标签为[GuruTabBarItem]。

  final List<GuruNavigationBarItem> items;

  /// showLabels
  /// [GuruNavigationBar] The navigation bar show labels.
  /// [GuruNavigationBar] 导航栏是否显示labels

  final bool? showLabels;

  /// onChange
  /// [GuruNavigationBar] The callback function for tab index change.
  /// [GuruNavigationBar] 标签页切换的回调函数

  final ValueChanged<int>? onChange;

  const GuruNavigationBar(
      {super.key,
      this.currentIndex = 0,
      required this.items,
      this.showLabels = false,
      this.onChange}) : assert(items.length >= 2),
       assert(items.length <= 5);
  

  @override
  State<GuruNavigationBar> createState() => _GuruNavigationBarState();
}

class _GuruNavigationBarState extends State<GuruNavigationBar> {
  final designSpec = GuruThemeDesignSpec.get().navigationBarDesignSpec;
  int index = 0;

  @override
  void initState() {
    setState(() {
      index = widget.currentIndex;
    });
    super.initState();
  }

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

  List<BottomNavigationBarItem> _buildNavigationBarViews() {
    final guruTheme = GuruTheme.of(context);
    final colorScheme = guruTheme.colorScheme;
    final navigationBarTheme = guruTheme.navigationBarTheme;

    final List<BottomNavigationBarItem> widgets = [];
    for (GuruNavigationBarItem item in widget.items) {
      widgets.add(BottomNavigationBarItem(
          icon: Image.asset(item.icon,
              width: widget.showLabels == true
                  ? designSpec.navigationBarLabelIconSize
                  : designSpec.navigationBarIconSize,
              height: widget.showLabels == true
                  ? designSpec.navigationBarLabelIconSize
                  : designSpec.navigationBarIconSize,
              color: navigationBarTheme.unSelctedColor ??
                  colorScheme.secondaryContentColor ??
                  Colors.white.withOpacity(0.4)),
          label: item.label,
          activeIcon: Image.asset(item.activeIcon,
              width: widget.showLabels == true
                  ? designSpec.navigationBarLabelIconSize
                  : designSpec.navigationBarIconSize,
              height: widget.showLabels == true
                  ? designSpec.navigationBarLabelIconSize
                  : designSpec.navigationBarIconSize,
              color: navigationBarTheme.selectedColor ??
                  colorScheme.primaryColor ??
                  const Color(0xFF5067ED))));
    }

    return widgets;
  }

  Widget _buildNavigationBarItem(GuruNavigationBarItem item, int index) {
    final guruTheme = GuruTheme.of(context);
    final colorScheme = guruTheme.colorScheme;
    final navigationBarTheme = guruTheme.navigationBarTheme;

    final iconSize = widget.showLabels == true
        ? designSpec.navigationBarLabelIconSize
        : designSpec.navigationBarIconSize;
    final unSelectColor = navigationBarTheme.unSelctedColor ??
        colorScheme.secondaryContentColor ??
        Colors.white.withOpacity(0.4);
    final selectColor = navigationBarTheme.selectedColor ??
        colorScheme.primaryColor ??
        const Color(0xFF5067ED);

    final icon = Image.asset(item.activeIcon,
        width: iconSize,
        height: iconSize,
        color: index == widget.currentIndex ? selectColor : unSelectColor);

    final label = SizedBox(
        width: designSpec.navigationBarItemWidth,
        child: Text(item.label ?? '',
            textAlign: TextAlign.center,
            style: TextStyle(
                fontWeight: GuruTheme.fwMedium,
                fontSize: 10,
                height: 1,
                color: index == widget.currentIndex
                    ? selectColor
                    : unSelectColor)));

    return TapWidget(
        inkWell: true,
        shape: const CircleBorder(),
        onTap: () {
          if (index != widget.currentIndex) {
            widget.onChange?.call(index);
            setState(() {
              index = index;
            });
          }
        },
        child: widget.showLabels == true
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [icon, const SizedBox(height: 3), label],
              )
            : SizedBox(
                width: designSpec.navigationBarItemWidth,
                height: designSpec.navigationBarHeight,
                child: Center(child: icon)));
  }

  Widget _buildNavigationBar1() {
    final guruTheme = GuruTheme.of(context);
    final colorScheme = guruTheme.colorScheme;
    final navigationBarTheme = guruTheme.navigationBarTheme;
    final paddingList = [];

    return BottomNavigationBar(
        items: _buildNavigationBarViews(),
        currentIndex: widget.currentIndex,
        type: navigationBarTheme.type ?? BottomNavigationBarType.fixed,
        iconSize: designSpec.navigationBarIconSize,
        selectedFontSize: widget.showLabels == true
            ? designSpec.navigationBarLabelFontSize
            : 0.0,
        unselectedFontSize: widget.showLabels == true
            ? designSpec.navigationBarLabelFontSize
            : 0.0,
        showSelectedLabels: widget.showLabels,
        showUnselectedLabels: widget.showLabels,
        selectedItemColor: navigationBarTheme.selectedColor ??
            colorScheme.primaryColor ??
            const Color(0xFF5067ED),
        unselectedItemColor: navigationBarTheme.unSelctedColor ??
            colorScheme.secondaryContentColor ??
            Colors.white.withOpacity(0.4),
        elevation: 0,
        onTap: (int index) {
          widget.onChange?.call(index);
        });
  }

  Widget _buildNavigationBar() {
    final List<Widget> items = [];

    for (var i = 0; i < widget.items.length; i++) {
      final item = widget.items[i];
      items.add(
        Expanded(child: Center(child: _buildNavigationBarItem(item, i)))
      );
    }

    return Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: items);
  }

  @override
  Widget build(BuildContext context) {
    final guruTheme = GuruTheme.of(context);
    final navigationBarTheme = guruTheme.navigationBarTheme;

    final paddingBottom = MediaQuery.of(context).padding.bottom;
    final paddingList = [designSpec.navigationBarSpacing2, designSpec.navigationBarSpacing3, designSpec.navigationBarSpacing4, designSpec.navigationBarSpacing5];

    return Stack(
      children: [
        FlexibleContainer(
            height: designSpec.navigationBarHeight + paddingBottom,
            color: navigationBarTheme.backgroundColor ?? Colors.white,
            padding: EdgeInsets.only(
              left: paddingList[widget.items.length - 2],
              right: paddingList[widget.items.length - 2],
              bottom: paddingBottom
            ),
            child: _buildNavigationBar()),
        Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: HorizontalDivider(
                color: navigationBarTheme.navigationBarTopDividerColor ??
                    Colors.black.withOpacity(0.08),
                bgColor: navigationBarTheme.navigationBarTopDividerColor ??
                    Colors.black.withOpacity(0.08),
                thickness:
                    navigationBarTheme.navigationBarTopDividerHeight ?? 0.5,
                height:
                    navigationBarTheme.navigationBarTopDividerHeight ?? 0.5))
      ],
    );
  }
}
