import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class UserDropdownMenu extends StatefulWidget {
  const UserDropdownMenu({super.key, required this.user});
  final UserModel? user;

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

class _UserDropdownMenuState extends State<UserDropdownMenu> {
  bool _isDropdownOpen = false;

  void _toggleDropdown() {
    setState(() {
      _isDropdownOpen = !_isDropdownOpen;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: () async {
            _toggleDropdown();
            await _showPopupMenu(context);
            setState(() {
              _isDropdownOpen = false;
            });
          },
          child: Row(
            children: [
              const SizedBox(width: 12),
              if (widget.user != null)
                Text(
                  '${widget.user!.firstName} ${widget.user!.lastName}',
                  style: Theme.of(context).textTheme.bodyLarge,
                ),
              const SizedBox(width: 12),
              Transform.rotate(
                angle: _isDropdownOpen ? -1.5708 : 1.5708,
                child: const Icon(
                  Icons.arrow_forward_ios,
                  color: Colors.white,
                  size: 16,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Future<void> _showPopupMenu(BuildContext context) async {
    final RenderBox overlay =
        Overlay.of(context).context.findRenderObject() as RenderBox;
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromLTRB(
        overlay.size.width,
        75,
        0,
        overlay.size.height,
      ),
      Offset.zero & overlay.size,
    );

    await showMenu(
      context: context,
      position: position,
      color: ColorsManager.whiteColors,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          bottomRight: Radius.circular(10),
          bottomLeft: Radius.circular(10),
        ),
      ),
      items: <PopupMenuEntry>[
        // PopupMenuItem(
        //   onTap: () {},
        //   child: ListTile(
        //     leading: SvgPicture.asset(Assets.accountSetting),
        //     title: Text(
        //       "Account Settings",
        //       style: context.textTheme.bodyMedium,
        //     ),
        //   ),
        // ),
        PopupMenuItem(
          onTap: () {
            context.go(RoutesConst.rolesAndPermissions);
          },
          child: ListTile(
            leading: SvgPicture.asset(Assets.userManagement),
            title: Text(
              "User Management",
              style: context.textTheme.bodyMedium,
            ),
          ),
        ),
        PopupMenuItem(
          onTap: () {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                    alignment: Alignment.center,
                    content: SizedBox(
                      height: 200,
                      width: 400,
                      child: Padding(
                        padding:
                            const EdgeInsets.only(top: 24, left: 24, right: 24),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Image.asset(
                              Assets.blackLogo,
                              height: 40,
                              width: 200,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 16),
                              child: Text(
                                'Log out of your Syncrow account',
                                style: Theme.of(context)
                                    .textTheme
                                    .bodyMedium!
                                    .copyWith(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w400,
                                      color: Colors.black,
                                    ),
                              ),
                            ),
                            const SizedBox(
                              height: 16,
                            ),
                            Row(
                              children: [
                                SizedBox.square(
                                  dimension: 80,
                                  child: CircleAvatar(
                                    backgroundColor: ColorsManager.whiteColors,
                                    child: SizedBox.square(
                                      dimension: 78,
                                      child: SvgPicture.asset(
                                        Assets.logoGrey,
                                        fit: BoxFit.fitHeight,
                                        height: 80,
                                      ),
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  width: 16,
                                ),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        '${widget.user?.firstName ?? ''} ${widget.user?.lastName}',
                                        style: Theme.of(context)
                                            .textTheme
                                            .titleMedium!
                                            .copyWith(
                                              color: Colors.black,
                                              fontWeight: FontWeight.bold,
                                              fontSize: 20,
                                            ),
                                      ),
                                      Text(
                                        ' ${widget.user?.email}',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                              color: Colors.black,
                                            ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    actionsAlignment: MainAxisAlignment.center,
                    actions: [
                      SizedBox(
                        width: 200,
                        child: GestureDetector(
                          onTap: () {
                            context.pop();
                          },
                          child: DefaultButton(
                            backgroundColor: ColorsManager.boxColor,
                            elevation: 1,
                            child: Text(
                              'Cancel',
                              style: Theme.of(context)
                                  .textTheme
                                  .bodyMedium!
                                  .copyWith(
                                    fontSize: 12,
                                    color: Colors.black,
                                  ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      GestureDetector(
                        onTap: () {
                          AuthBloc.logout(context);
                          context.go(RoutesConst.auth);
                        },
                        child: SizedBox(
                          width: 200,
                          child: DefaultButton(
                            elevation: 1,
                            child: Text(
                              'Logout',
                              style: Theme.of(context)
                                  .textTheme
                                  .bodyMedium!
                                  .copyWith(fontSize: 12, color: Colors.white),
                            ),
                          ),
                        ),
                      ),
                    ]);
              },
            );
          },
          child: ListTile(
            leading: SvgPicture.asset(Assets.signOut),
            title: Text(
              "Log Out",
              style: context.textTheme.bodyMedium,
            ),
          ),
        ),
      ],
    ).then((value) {
      setState(() {
        _isDropdownOpen = false;
      });
    });
  }
}
