import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/views/pages/user/notifications/notifications_page.dart';
import 'package:test_sa/views/pages/user/notifications/unread_chat_list.dart';

import '../../controllers/providers/api/user_provider.dart';
import '../../models/user.dart';

class AppBarWidget extends StatefulWidget {
  final VoidCallback onDrawerPress;

  const AppBarWidget({Key? key, required this.onDrawerPress}) : super(key: key);

  @override
  State<AppBarWidget> createState() => _AppBarWidgetState();
}

class _AppBarWidgetState extends State<AppBarWidget> with TickerProviderStateMixin {
  late AnimationController _leftController;
  late AnimationController _rightController;
  late Animation<Offset> _leftSlideAnimation;
  late Animation<double> _leftFadeAnimation;
  late Animation<Offset> _rightSlideAnimation;
  late Animation<double> _rightFadeAnimation;

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

    // Profile section animation (left to right with fade)
    _leftController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _leftSlideAnimation = Tween<Offset>(
      begin: const Offset(-0.3, 0.0),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _leftController,
      curve: Curves.easeOutCubic,
    ));

    _leftFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _leftController,
      curve: Curves.easeIn,
    ));

    // Action icons animation (right to left with fade)
    _rightController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _rightSlideAnimation = Tween<Offset>(
      begin: const Offset(0.3, 0.0),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _rightController,
      curve: Curves.easeOutCubic,
    ));

    _rightFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _rightController,
      curve: Curves.easeIn,
    ));

    // Start animations with slight delay between them
    _leftController.forward();
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) _rightController.forward();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      titleSpacing: 0,
      title: Consumer<UserProvider>(builder: (context, snapshot, _) {
        return Row(
          // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // Profile section with left-to-right fade animation
            SlideTransition(
              position: _leftSlideAnimation,
              child: FadeTransition(
                opacity: _leftFadeAnimation,
                child: CircleAvatar(
                  radius: 24,
                  backgroundColor: context.isDark ? AppColor.neutral50 : AppColor.neutral40,
                  child: Padding(
                    padding: const EdgeInsets.all(1), // Border radius
                    child: ClipOval(
                      child: snapshot.profileImage != null
                          ? Image.file(snapshot.profileImage!) // Added null check
                          : (snapshot.user?.profilePhotoName?.isNotEmpty ?? false)
                              ? Image.network(snapshot.user!.profilePhotoName!) // Added null check
                              : const Icon(Icons.person, size: 24, color: Colors.white),
                    ),
                  ),
                ).onPress(widget.onDrawerPress),
              ),
            ),
            8.width,
            Expanded(
              child: SlideTransition(
                position: _leftSlideAnimation,
                child: FadeTransition(
                  opacity: _leftFadeAnimation,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    spacing: 4,
                    children: [
                      Text(
                        snapshot.user?.username ?? "",
                        style: AppTextStyles.heading6.copyWith(color: AppColor.headingTextColor(context), fontSize: context.isTablet() ? 14 : null),
                      ),
                      Text(
                        snapshot.user?.type?.name.toCamelCase ?? "",
                        style: AppTextStyles.bodyText.copyWith(color: AppColor.lightTextColor(context), fontSize: context.isTablet() ? 12 : null),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            const Spacer(),
            // Action icons with right-to-left fade animation
            SlideTransition(
              position: _rightSlideAnimation,
              child: FadeTransition(
                opacity: _rightFadeAnimation,
                child: Consumer<SettingProvider>(builder: (context, settingProvider, child) {
                  return MenuAnchor(
                    style: MenuStyle(
                      backgroundColor: WidgetStateProperty.all(AppColor.background(context)),
                      shape: WidgetStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          side: BorderSide(color: AppColor.borderColor(context), width: 1),
                        ),
                      ),
                      padding: WidgetStateProperty.all(
                        EdgeInsets.symmetric(
                          horizontal: 0.toScreenWidth,
                          vertical: 8.toScreenHeight,
                        ),
                      ),
                      elevation: WidgetStateProperty.all(0),
                    ),
                    menuChildren: Provider.of<UserProvider>(context, listen: false).user?.assetGroups?.map<MenuItemButton>((value) {
                          return MenuItemButton(
                            onPressed: () async {
                              if (settingProvider.assetGroup != value) {
                                AssetGroup? tempGroup = ApiManager.instance.assetGroup;
                                ApiManager.instance.assetGroup = value;

                                Utils.showLoading(context);
                                bool isSuccess = await context.userProvider.userChangeAssetGroup();
                                Utils.hideLoading(context);
                                if (isSuccess) {
                                  await context.userProvider.getMobilePermissionByUser();
                                  settingProvider.setAssetGroup(value);
                                  WidgetsBinding.instance.addPostFrameCallback((_) {
                                    context.settingProvider.setUser(ApiManager.instance.user!);
                                    context.userProvider.setUser(ApiManager.instance.user!);
                                    DashBoardProvider dashBoardProvider = Provider.of<DashBoardProvider>(context, listen: false);
                                    dashBoardProvider.setTabs(userType: settingProvider.user!.type!, context: context);
                                    dashBoardProvider.getDashBoardCount(usersType: settingProvider.user!.type!);
                                    dashBoardProvider.resetRequestDataList();
                                    if (dashBoardProvider.currentListIndex == null) {
                                    } else {
                                      dashBoardProvider.getRequestDetail(usersType: settingProvider.user!.type!, status: dashBoardProvider.tabs[dashBoardProvider.currentListIndex!].tag);
                                    }
                                  });
                                } else {
                                  ApiManager.instance.assetGroup = tempGroup;
                                  context.showConfirmDialog("Failed, Please Try again");
                                }
                              }
                            },
                            child: Text(value.name ?? "", style: AppTextStyles.bodyText2.copyWith(color: AppColor.headingTextColor(context))),
                          );
                        }).toList() ??
                        [],
                    builder: (_, MenuController controller, Widget? child) {
                      return Container(
                        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: AppColor.assetGroupBackground(context),
                          border: Border.all(color: AppColor.white936.withValues(alpha: .03), width: 1),
                          boxShadow: [
                            BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 0), spreadRadius: 0),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          spacing: 8,
                          children: [
                            Text(
                              settingProvider.assetGroup?.name ?? "",
                              style: AppTextStyles.bodyText2.copyWith(color: AppColor.headingTextColor(context)),
                            ),
                            Icon(Icons.keyboard_arrow_down, color: AppColor.headingTextColor(context), size: 20),
                          ],
                        ),
                      ).onPress(() {
                        if (controller.isOpen) {
                          controller.close();
                        } else {
                          controller.open();
                        }
                      });
                    },
                  );
                }),
              ),
            ),
            8.width,
            SlideTransition(
              position: _rightSlideAnimation,
              child: FadeTransition(
                opacity: _rightFadeAnimation,
                child: Row(
                  children: [
                    if (context.settingProvider.isUserFlowMedical) ...[
                      IconButton(
                        icon: ("dashboard/chat").toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)),
                        padding: EdgeInsets.zero,
                        visualDensity: VisualDensity.compact,
                        tooltip: "Notifications",
                        onPressed: () {
                          Navigator.of(context).push(CupertinoPageRoute(builder: (_) => UnReadChatList()));
                        },
                      ),
                    ],
                    IconButton(
                      icon: ("dashboard/notification").toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)),
                      padding: EdgeInsets.zero,
                      visualDensity: VisualDensity.compact,
                      tooltip: "Notifications",
                      onPressed: () {
                        Navigator.of(context).pushNamed(NotificationsPage.id);
                      },
                    ),
                  ],
                ),
              ),
            ),
          ],
        ).paddingOnly(start: 16, end: 08);
      }),
    );
  }
}
