import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/model/permission_option_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class PermissionManagement extends StatefulWidget {
  final UsersBloc? bloc;
  const PermissionManagement({Key? key, this.bloc}) : super(key: key);

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

class _PermissionManagementState extends State<PermissionManagement> {
  void toggleOptionById(String id) {
    setState(() {
      for (var mainOption in widget.bloc!.permissions) {
        if (mainOption.id == id) {
          final isChecked =
              checkifOneOfthemChecked(mainOption) == CheckState.all;
          mainOption.isChecked = !isChecked;

          for (var subOption in mainOption.subOptions) {
            subOption.isChecked = !isChecked;
            for (var child in subOption.subOptions) {
              child.isChecked = !isChecked;
            }
          }
          return;
        }

        for (var subOption in mainOption.subOptions) {
          if (subOption.id == id) {
            subOption.isChecked = !subOption.isChecked;
            for (var child in subOption.subOptions) {
              child.isChecked = subOption.isChecked;
            }
            mainOption.isChecked =
                mainOption.subOptions.every((sub) => sub.isChecked);
            return;
          }

          for (var child in subOption.subOptions) {
            if (child.id == id) {
              child.isChecked = !child.isChecked;
              subOption.isChecked =
                  subOption.subOptions.every((child) => child.isChecked);
              mainOption.isChecked =
                  mainOption.subOptions.every((sub) => sub.isChecked);
              return;
            }
          }
        }
      }
    });
  }

  CheckState checkifOneOfthemChecked(PermissionOption mainOption) {
    bool allSelected = true;
    bool someSelected = false;

    for (var subOption in mainOption.subOptions) {
      if (subOption.isChecked) {
        someSelected = true;
      } else {
        allSelected = false;
      }

      for (var child in subOption.subOptions) {
        if (child.isChecked) {
          someSelected = true;
        } else {
          allSelected = false;
        }
      }
    }

    if (allSelected) {
      return CheckState.all;
    } else if (someSelected) {
      return CheckState.some;
    } else {
      return CheckState.none;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: const EdgeInsets.all(8),
      itemCount: widget.bloc!.permissions.length,
      itemBuilder: (context, index) {
        final option = widget.bloc!.permissions[index];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                InkWell(
                  // onTap: () => toggleOptionById(option.id),
                  child: Builder(
                    builder: (context) {
                      final checkState = checkifOneOfthemChecked(option);

                      if (checkState == CheckState.all) {
                        return Image.asset(
                          Assets.CheckBoxChecked,
                          width: 20,
                          height: 20,
                        );
                      } else if (checkState == CheckState.some) {
                        return Image.asset(
                          Assets.rectangleCheckBox,
                          width: 20,
                          height: 20,
                        );
                      } else {
                        return Image.asset(
                          Assets.emptyBox,
                          width: 20,
                          height: 20,
                        );
                      }
                    },
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  ' ${option.title.isNotEmpty ? option.title[0].toUpperCase() : ''}${option.title.substring(1)}',
                  style: context.textTheme.bodyMedium?.copyWith(
                      fontWeight: FontWeight.w700,
                      fontSize: 12,
                      color: ColorsManager.blackColor),
                ),
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            ...option.subOptions.map((subOption) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    color: option.isHighlighted
                        ? Colors.blue.shade50
                        : Colors.white,
                    child: Row(
                      children: [
                        InkWell(
                          // onTap: () => toggleOptionById(subOption.id),
                          child: Builder(
                            builder: (context) {
                              final checkState =
                                  checkifOneOfthemChecked(PermissionOption(
                                id: subOption.id,
                                title: subOption.title,
                                subOptions: [subOption],
                              ));

                              if (checkState == CheckState.all) {
                                return Image.asset(
                                  Assets.CheckBoxChecked,
                                  width: 20,
                                  height: 20,
                                );
                              } else if (checkState == CheckState.some) {
                                return Image.asset(
                                  Assets.rectangleCheckBox,
                                  width: 20,
                                  height: 20,
                                );
                              } else {
                                return Image.asset(
                                  Assets.emptyBox,
                                  width: 20,
                                  height: 20,
                                );
                              }
                            },
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          ' ${subOption.title.isNotEmpty ? subOption.title[0].toUpperCase() : ''}${subOption.title.substring(1)}',
                          style: context.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w700,
                              fontSize: 12,
                              color: ColorsManager.lightGreyColor),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 50.0),
                    child: GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        mainAxisSpacing: 2.0,
                        crossAxisSpacing: 0.2,
                        childAspectRatio: 5,
                      ),
                      itemCount: subOption.subOptions.length,
                      itemBuilder: (context, index) {
                        final child = subOption.subOptions[index];
                        return Container(
                          color: option.isHighlighted
                              ? Colors.blue.shade50
                              : Colors.white,
                          child: Row(
                            children: [
                              Builder(
                                builder: (context) {
                                  final checkState =
                                      checkifOneOfthemChecked(PermissionOption(
                                    id: child.id,
                                    title: child.title,
                                    subOptions: [child],
                                  ));

                                  if (checkState == CheckState.all) {
                                    return Image.asset(
                                      Assets.CheckBoxChecked,
                                      width: 20,
                                      height: 20,
                                    );
                                  } else if (checkState == CheckState.some) {
                                    return Image.asset(
                                      Assets.rectangleCheckBox,
                                      width: 20,
                                      height: 20,
                                    );
                                  } else {
                                    return Image.asset(
                                      Assets.emptyBox,
                                      width: 20,
                                      height: 20,
                                    );
                                  }
                                },
                              ),
                              const SizedBox(width: 8),
                              Text(
                                ' ${child.title.isNotEmpty ? child.title[0].toUpperCase() : ''}${child.title.substring(1)}',
                                style: context.textTheme.bodyMedium?.copyWith(
                                    fontWeight: FontWeight.w400,
                                    fontSize: 12,
                                    color: ColorsManager.lightGreyColor),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  )
                ],
              );
            }).toList(),
          ],
        );
      },
    );
  }
}


   // Container(
                            //   height: 50,
                            //   width: 120,
                            //   child: CheckboxListTile(
                            //     activeColor: ColorsManager.dialogBlueTitle,
                            //     selectedTileColor: child.isHighlighted
                            //         ? Colors.blue.shade50
                            //         : Colors.white,
                            //     dense: true,
                            //     controlAffinity:
                            //         ListTileControlAffinity.leading,
                            //     title: Text(
                            //       child.title,
                            //       style: context.textTheme.bodyMedium?.copyWith(
                            //           fontWeight: FontWeight.w400,
                            //           fontSize: 12,
                            //           color: ColorsManager.lightGreyColor),
                            //     ),
                            //     value: child.isChecked,
                            //     onChanged: (value) =>
                            //         toggleOptionById(child.id),
                            //     enabled: false,
                            //   ),
                            // ),