import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttericon/font_awesome5_icons.dart';
import 'package:unit2/screens/docsms/index.dart';
import 'package:unit2/screens/unit2/homepage.dart/module-screen.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/global_context.dart';
import 'package:unit2/utils/qr_scanner.dart';
import '../../../../bloc/docsms/docsms_bloc.dart';

class DashBoard extends StatelessWidget {
  final List<Module> roles;
  final int userId;
  const DashBoard({super.key, required this.roles,required this.userId});
  @override
  Widget build(BuildContext context) {
    List<String> finishRoles = [];
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
      height: MediaQuery.of(context).size.height,
      ////listview builder
      child: ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          itemCount: roles.length,
          itemBuilder: (BuildContext context, int index) {

            ////  gridview.count
            return roles[index].roles.isNotEmpty
                ? SizedBox(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          roles[index].name.toUpperCase(),
                          style: Theme.of(context)
                              .textTheme
                              .labelLarge!
                              .copyWith(fontSize: 12),
                        ),
                        const SizedBox(
                          height: 8,
                        ),
                        GridView.count(
                            shrinkWrap: true,
                            crossAxisCount: 4,
                            crossAxisSpacing: 8,
                            mainAxisSpacing: 10,
                            physics: const BouncingScrollPhysics(),
                            padding: const EdgeInsets.symmetric(
                                vertical: 5, horizontal: 5),
                            children: roles[index].roles.map((role) {
                              if (role.role.name!.toLowerCase() ==
                                      'qr code scanner' &&
                                  !finishRoles.contains("security")) {
                                    print("1 true");
                                finishRoles.add('scanner');
                                for (var element in role.role.modules!) {
                                  if (element!.name!.toLowerCase() == 'unit2') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 9 && 
                                          element.operations!
                                              .contains("read")) {
                                        return CardLabel(
                                          ontap: () {
                                            PassCheckArguments passCheckArguments = PassCheckArguments(roleId: role.role.id!, userId: userId);
                                            Navigator.pushNamed(context, '/pass-check',arguments: passCheckArguments);
                                          },
                                          icon: role.icon,
                                          title: "Pass Check",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container();
                              } else if (role.role.name!.toLowerCase() ==
                                      'security guard' &&
                                  !finishRoles.contains('scanner')) {
                                        print("2 true");
                                finishRoles.add('security');
                                for (var element in role.role.modules!) {
                                  if (element!.name!.toLowerCase() == 'unit2') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 9 &&
                                          element.operations!
                                              .contains("read")) {
                                        return CardLabel(
                                          ontap: () {},
                                          icon: role.icon,
                                          title: "Pass Check",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container(color: Colors.red,);
                              } else if (role.role.name!.toLowerCase() ==
                                  'field surveyor') {
                                        print("3 true");
                                for (var element in role.role.modules!) {
                                  if (element!.name!.toLowerCase() == 'rpass') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 11 &&
                                          element.operations!
                                              .contains("read")) {
                                        return CardLabel(
                                          ontap: () {},
                                          icon: role.icon,
                                          title: "Field Surveyor",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container();
                              } else if (role.role.name!.toLowerCase() ==
                                  'process server') {
                                        print("4 true");
                                for (var element in role.role.modules!) {
                                  if (element!.name!.toLowerCase() ==
                                      'document management') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 3 &&
                                          element.operations!
                                              .contains("read")) {
                                        return CardLabel(
                                          ontap: () async {
                                            String? qrBarcode =
                                                await qrScanner();
                                            if (qrBarcode != null) {
                                              Navigator.push(NavigationService.navigatorKey.currentContext!, MaterialPageRoute(builder:
                                                  (BuildContext context) {
                                                return BlocProvider(
                                                  create: (context) => DocsmsBloc()
                                                    ..add(LoadDocument(
                                                        documentId: qrBarcode)),
                                                  child:
                                                      const AutoReceiveDocument(),
                                                );
                                              }));
                                            }
                                          },
                                          icon: role.icon,
                                          title: "Process Server",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container();
                              }     else if (role.role.name!.toLowerCase() ==
                                      'establishment point-person' &&
                                  !finishRoles.contains('superadmin')) {
                                finishRoles.add('establishment point-person');
                                for (var element in role.role.modules!) {
                                      print("5 true");
                                  if (element!.name!.toLowerCase() == 'unit2') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 7 &&
                                          element.operations!
                                              .contains("upload")) {
                                        return CardLabel(
                                          ontap: () {},
                                          icon: FontAwesome5.building,
                                          title: "Establishment",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container();
                      
                              }  else if (role.role.name!.toLowerCase() ==
                                      'establishment point-person' &&
                                  !finishRoles.contains('superadmin')) {
                                finishRoles.add('establishment point-person');
                                for (var element in role.role.modules!) {
                                  if (element!.name!.toLowerCase() == 'unit2') {
                                    for (var element in element.objects!) {
                                      if (element!.id == 7 &&
                                          element.operations!
                                              .contains("upload")) {
                                        return CardLabel(
                                          ontap: () {},
                                          icon: FontAwesome5.building,
                                          title: "Establishment",
                                        );
                                      }
                                    }
                                  }
                                }
                                return Container();
                      
                              } else{
                                return Wrap();
                              }
                              
                          
                            }).toList()),
                        const SizedBox(
                          height: 8,
                        )
                      ],
                    ),
                  )
                : Container();
          }),
    );
  }
}

class PassCheckArguments{
  final int roleId;
  final int userId;
  const PassCheckArguments({required this.roleId, required this.userId});
}

// ignore: must_be_immutable
class CardLabel extends StatelessWidget {
  final String title;
  final IconData icon;
  final Function()? ontap;
  const CardLabel(
      {super.key,
      required this.icon,
      required this.title,
      required this.ontap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ontap,
      child: Container(
        padding: const EdgeInsetsDirectional.fromSTEB(8, 5, 8, 13),
        alignment: Alignment.center,
        decoration: const BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(color: Colors.black12, spreadRadius: 2, blurRadius: 3)
            ],
            borderRadius: BorderRadius.all(Radius.circular(8))),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Icon(
                  icon,
                  size: 20,
                  weight: 100,
                  grade: 100,
                  color: second,
                ),
              ),
              const SizedBox(
                height: 5,
              ),
              Text(
                title,
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.labelLarge!.copyWith(
                    fontSize: blockSizeVertical * 1.2,
                    fontWeight: FontWeight.bold),
              ),
            ]),
      ),
    );
  }
}
