// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/utils/tools/tools.dart';
import 'package:qadirneyriz/widgets/ExpansionTileCustom.dart';
import 'package:qadirneyriz/widgets/checkBox_inTile.dart';
import 'package:qadirneyriz/widgets/custom_button.dart';
import 'package:qadirneyriz/widgets/custom_textfield.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class AddUserDiolog extends StatefulWidget {
  AddUserDiolog({
    super.key,
  });

  @override
  State<AddUserDiolog> createState() => _AddUserDiologState();
}

class _AddUserDiologState extends State<AddUserDiolog> {
  final TextEditingController nameController = TextEditingController();

  final TextEditingController mobileController = TextEditingController();

  final TextEditingController passwordController = TextEditingController();

  int selectedRole = 1;

  @override
  Widget build(BuildContext context) {
    final List<MemberRole> roles = [
      MemberRole(
        roleId: 1,
        roleName: AppLocalizations.of(context)!.normaluser,
      ),
      // MemberRole(roleId: 2, roleName: 'اپراتور'),
    ];
    return Consumer<GlobalState>(
      builder: (context, value, child) {
        return Dialog(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min, // برای اندازه‌گیری درست دیالوگ
                children: [
                  Text(
                    AppLocalizations.of(context)!.newmember,
                  ),
                  CustomTextField(
                      label: '',
                      hintText: AppLocalizations.of(context)!.nameandfamilyname,
                      paddingVertical: 0,
                      textEditingController: nameController,
                      textInputType: TextInputType.text),
                  CustomTextField(
                      label: '',
                      paddingVertical: 0,
                      hintText: AppLocalizations.of(context)!.phonenumber,
                      textEditingController: mobileController,
                      textInputType: TextInputType.phone),
                  CustomTextField(
                      label: '',
                      paddingVertical: 0,
                      hintText: AppLocalizations.of(context)!.password,
                      isPass: true,
                      textEditingController: passwordController,
                      textInputType: TextInputType.visiblePassword),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: ExpansionTileCustom(
                      isForm: true,
                      subTitile: '',
                      title: AppLocalizations.of(context)!.role,
                      widgets: <Widget>[
                        Column(
                          children: roles.map((role) {
                            bool isSelected = selectedRole == role.roleId;
                            return CheckBoxInTile(
                              backColor:
                                  isSelected ? Color(0xff06CF64) : Colors.white,
                              textColor:
                                  isSelected ? Colors.white : Colors.black,
                              text: role.roleName,
                              hasIcon: false,
                              onTap: () {
                                setState(() {
                                  selectedRole = role.roleId;
                                });
                              },
                            );
                          }).toList(),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 60,
                  ),
                  submit(value, context),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  CustomButton submit(GlobalState state, BuildContext context) {
    switch (state.statusAddNewUser) {
      case Status.loading:
        return CustomButton(
          hieght: 40,
          width: double.infinity,
          text: AppLocalizations.of(context)!.loading,
          fontSize: 13,
          onPressed: null,
          borderRadius: 10,
        );

      default:
        return CustomButton(
          hieght: 40,
          width: double.infinity,
          text: AppLocalizations.of(context)!.add,
          fontSize: 13,
          onPressed: () async {
            if (nameController.text == '') {
              // call add new subject

              Tools.showCustomSnackBar(
                text: AppLocalizations.of(context)!.enternameandfamily,
                isError: true,
                context,
              );
            } else if (mobileController.text == '') {
              Tools.showCustomSnackBar(
                text: AppLocalizations.of(context)!.enterphonenumber,
                isError: true,
                context,
              );
            } else if (passwordController.text == '') {
              Tools.showCustomSnackBar(
                text: AppLocalizations.of(context)!.enterpassword,
                isError: true,
                context,
              );
            }
            // else if (selectedRole == null) {
            //   Tools.showCustomSnackBar(
            //     text: 'نقش کاربر وارد کنید!',
            //     isError: true,
            //     context,
            //   );
            // }
            else {
              final status = await state.addNewUser(
                  name: nameController.text,
                  mobile: mobileController.text,
                  role: selectedRole,
                  password: passwordController.text);
              if (status == Status.ready) {
                // call refrresh users
                await state.getUsers(refresh: true);
                Tools.showCustomSnackBar(
                  text: AppLocalizations.of(context)!.useradded,
                  isError: false,
                  context,
                );
                context.pop();
              } else {
                Tools.showCustomSnackBar(
                  text: state.errorsAddNewUser == null
                      ? state.messageAddNewUser ??
                          AppLocalizations.of(context)!.haserror
                      : Tools.combineErrorMessages(
                          state.errorsAddNewUser ?? {}),
                  isError: true,
                  context,
                );
              }
            }
          },
          borderRadius: 10,
        );
    }
  }
}

class MemberRole {
  final int roleId;
  final String roleName;
  MemberRole({
    required this.roleId,
    required this.roleName,
  });
}
