import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/date_time_widget.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_event.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_state.dart';
import 'package:syncrow_web/pages/visitor_password/view/access_type_radio_group.dart';
import 'package:syncrow_web/pages/visitor_password/view/add_device_dialog.dart';
import 'package:syncrow_web/pages/visitor_password/view/repeat_widget.dart';
import 'package:syncrow_web/pages/visitor_password/view/responsive_fields_row.dart';
import 'package:syncrow_web/pages/visitor_password/view/usage_frequency_radio_group.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/style.dart';

class VisitorPasswordDialog extends StatelessWidget {
  const VisitorPasswordDialog({super.key});

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final text = Theme.of(context)
        .textTheme
        .bodySmall!
        .copyWith(color: Colors.black, fontSize: 13);
    return BlocProvider(
      create: (context) => VisitorPasswordBloc(),
      child: BlocListener<VisitorPasswordBloc, VisitorPasswordState>(
        listener: (context, state) {
          final visitorBloc = BlocProvider.of<VisitorPasswordBloc>(context);
          if (state is SuccessState) {
            visitorBloc
                .stateDialog(
                    context: context,
                    message: 'Password Created Successfully',
                    title: 'Sent Successfully',
                    widgeta: Column(
                      children: [
                        if (visitorBloc.passwordStatus!.failedOperations.isNotEmpty)
                          Column(
                            children: [
                              const Text('Failed Devices'),
                              SizedBox(
                                width: 200,
                                height: 50,
                                child: ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  shrinkWrap: true,
                                  itemCount: visitorBloc
                                      .passwordStatus!.failedOperations.length,
                                  itemBuilder: (context, index) {
                                    return Container(
                                      margin: const EdgeInsets.all(5),
                                      decoration: containerDecoration,
                                      height: 45,
                                      child: Center(
                                          child: Text(visitorBloc.passwordStatus!
                                              .failedOperations[index].deviceName)),
                                    );
                                  },
                                ),
                              ),
                            ],
                          ),
                        if (visitorBloc.passwordStatus!.successOperations.isNotEmpty)
                          Column(
                            children: [
                              const Text('Success Devices'),
                              SizedBox(
                                width: 200,
                                height: 50,
                                child: ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  shrinkWrap: true,
                                  itemCount: visitorBloc
                                      .passwordStatus!.successOperations.length,
                                  itemBuilder: (context, index) {
                                    return Container(
                                      margin: const EdgeInsets.all(5),
                                      decoration: containerDecoration,
                                      height: 45,
                                      child: Center(
                                          child: Text(visitorBloc.passwordStatus!
                                              .successOperations[index].deviceName)),
                                    );
                                  },
                                ),
                              ),
                            ],
                          ),
                      ],
                    ))
                .then((v) {
              Navigator.of(context).pop(v);
            });
          } else if (state is FailedState) {
            visitorBloc.stateDialog(
              context: context,
              message: state.message,
              title: 'Something went wrong',
            );
          }
        },
        child: BlocBuilder<VisitorPasswordBloc, VisitorPasswordState>(
          builder: (BuildContext context, VisitorPasswordState state) {
            final visitorBloc = BlocProvider.of<VisitorPasswordBloc>(context);
            final isRepeat =
                state is IsRepeatState ? state.repeat : visitorBloc.repeat;
            return AlertDialog(
              backgroundColor: Colors.white,
              title: Text(
                'Create visitor password',
                style: Theme.of(context).textTheme.headlineLarge!.copyWith(
                    fontWeight: FontWeight.w400, fontSize: 24, color: Colors.black),
              ),
              content: state is LoadingInitialState
                  ? const Center(child: CircularProgressIndicator())
                  : SingleChildScrollView(
                      child: Form(
                        key: visitorBloc.forgetFormKey,
                        child: Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: ListBody(
                            children: <Widget>[
                              NameAndEmailFields(
                                nameController: visitorBloc.userNameController,
                                emailController: visitorBloc.emailController,
                                nameValidator: visitorBloc.validate,
                                emailValidator: visitorBloc.validateEmail,
                              ),
                              const SizedBox(
                                height: 15,
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  AccessTypeRadioGroup(
                                    selectedType: state is PasswordTypeSelected
                                        ? state.selectedType
                                        : null,
                                    accessTypeSelected:
                                        visitorBloc.accessTypeSelected,
                                    onTypeSelected: (value) {
                                      context
                                          .read<VisitorPasswordBloc>()
                                          .add(SelectPasswordType(value));
                                    },
                                    visitorBloc: visitorBloc,
                                  ),

                                  if (visitorBloc.accessTypeSelected ==
                                      'Online Password')
                                    Text(
                                      'Only currently online devices can be selected. It is recommended to use when the device network is stable, and the system randomly generates a digital password',
                                      style: Theme.of(context)
                                          .textTheme
                                          .bodySmall!
                                          .copyWith(
                                              fontWeight: FontWeight.w400,
                                              color: ColorsManager.grayColor,
                                              fontSize: 9),
                                    ),
                                  if (visitorBloc.accessTypeSelected ==
                                      'Offline Password')
                                    Text(
                                      'Unaffected by the online status of the device, you can select online or offline device, and the system randomly generates a digital password',
                                      style: Theme.of(context)
                                          .textTheme
                                          .bodySmall!
                                          .copyWith(
                                              fontWeight: FontWeight.w400,
                                              color: ColorsManager.grayColor,
                                              fontSize: 9),
                                    ),
                                  // if (visitorBloc.accessTypeSelected == 'Dynamic Password')
                                  //   Text(
                                  //     'Quick and short-acting password, only valid within 5 minutes after creation, the system randomly generates a digital password.',
                                  //     style: Theme.of(context).textTheme.bodySmall!.copyWith(
                                  //         fontWeight: FontWeight.w400,
                                  //         color: ColorsManager.grayColor,
                                  //         fontSize: 9),
                                  //   ),
                                  const SizedBox(
                                    height: 20,
                                  )
                                ],
                              ),
                              if (visitorBloc.accessTypeSelected ==
                                  'Dynamic Password')
                                const SizedBox()
                              else
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Text(
                                          '* ',
                                          style: Theme.of(context)
                                              .textTheme
                                              .bodyMedium!
                                              .copyWith(color: Colors.red),
                                        ),
                                        Text(
                                          'Usage Frequency',
                                          style: text,
                                        ),
                                      ],
                                    ),
                                    UsageFrequencyRadioGroup(
                                      selectedFrequency:
                                          state is UsageFrequencySelected
                                              ? state.selectedFrequency
                                              : null,
                                      usageFrequencySelected:
                                          visitorBloc.usageFrequencySelected,
                                      onFrequencySelected: (value) {
                                        context
                                            .read<VisitorPasswordBloc>()
                                            .add(SelectUsageFrequency(value));
                                      },
                                    ),

                                    //One-Time
                                    if (visitorBloc.usageFrequencySelected ==
                                            'One-Time' &&
                                        visitorBloc.accessTypeSelected ==
                                            'Online Password')
                                      Text(
                                        'Within the validity period, each device can be unlocked only once.',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                                color: ColorsManager.grayColor,
                                                fontSize: 9),
                                      ),
                                    if (visitorBloc.usageFrequencySelected ==
                                            'One-Time' &&
                                        visitorBloc.accessTypeSelected ==
                                            'Offline Password')
                                      Text(
                                        'Within the validity period, each device can be unlocked only once, and the maximum validity period is 6 hours',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                                color: ColorsManager.grayColor,
                                                fontSize: 9),
                                      ),

                                    // Periodic
                                    if (visitorBloc.usageFrequencySelected ==
                                            'Periodic' &&
                                        visitorBloc.accessTypeSelected ==
                                            'Offline Password')
                                      Text(
                                        'Within the validity period, there is no limit to the number of times each device can be unlocked, and it should be used at least once within 24 hours after the entry into force.',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                                color: ColorsManager.grayColor,
                                                fontSize: 9),
                                      ),

                                    if (visitorBloc.usageFrequencySelected ==
                                            'Periodic' &&
                                        visitorBloc.accessTypeSelected ==
                                            'Online Password')
                                      Text(
                                        'Within the validity period, there is no limit to the number of times each device can be unlocked.',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                                color: ColorsManager.grayColor,
                                                fontSize: 9),
                                      ),
                                  ],
                                ),
                              const SizedBox(
                                height: 20,
                              ),
                              if ((visitorBloc.usageFrequencySelected !=
                                          'One-Time' ||
                                      visitorBloc.accessTypeSelected !=
                                          'Offline Password') &&
                                  (visitorBloc.usageFrequencySelected != ''))
                                DateTimeWebWidget(
                                    isRequired: true,
                                    title: 'Access Period',
                                    size: size,
                                    endTime: () {
                                      if (visitorBloc.usageFrequencySelected ==
                                              'Periodic' &&
                                          visitorBloc.accessTypeSelected ==
                                              'Offline Password') {
                                        visitorBloc.add(SelectTimeEvent(
                                            context: context, isEffective: false));
                                      } else {
                                        visitorBloc.add(SelectTimeVisitorPassword(
                                            context: context,
                                            isStart: false,
                                            isRepeat: false));
                                      }
                                    },
                                    startTime: () {
                                      if (visitorBloc.usageFrequencySelected ==
                                              'Periodic' &&
                                          visitorBloc.accessTypeSelected ==
                                              'Offline Password') {
                                        visitorBloc.add(SelectTimeEvent(
                                            context: context, isEffective: true));
                                      } else {
                                        visitorBloc.add(SelectTimeVisitorPassword(
                                            context: context,
                                            isStart: true,
                                            isRepeat: false));
                                      }
                                    },
                                    firstString:
                                        (visitorBloc.usageFrequencySelected ==
                                                    'Periodic' &&
                                                visitorBloc.accessTypeSelected ==
                                                    'Offline Password')
                                            ? visitorBloc.effectiveTime
                                            : visitorBloc.startTimeAccess,
                                    secondString: (visitorBloc
                                                    .usageFrequencySelected ==
                                                'Periodic' &&
                                            visitorBloc.accessTypeSelected ==
                                                'Offline Password')
                                        ? visitorBloc.expirationTime
                                        : visitorBloc.endTimeAccess,
                                    icon: Assets.calendarIcon),
                              const SizedBox(
                                height: 10,
                              ),
                              Text(
                                visitorBloc.accessPeriodValidate,
                                style: Theme.of(context)
                                    .textTheme
                                    .bodyMedium!
                                    .copyWith(color: ColorsManager.red),
                              ),
                              const SizedBox(
                                height: 20,
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        '* ',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodyMedium!
                                            .copyWith(color: Colors.red),
                                      ),
                                      Text(
                                        'Access Devices',
                                        style: text,
                                      ),
                                    ],
                                  ),
                                  Text(
                                    'Within the validity period, each device can be unlocked only once.',
                                    style: Theme.of(context)
                                        .textTheme
                                        .bodySmall!
                                        .copyWith(
                                            fontWeight: FontWeight.w400,
                                            color: ColorsManager.grayColor,
                                            fontSize: 9),
                                  ),
                                  const SizedBox(
                                    height: 20,
                                  ),
                                  if (visitorBloc.usageFrequencySelected ==
                                          'Periodic' &&
                                      visitorBloc.accessTypeSelected ==
                                          'Online Password')
                                    SizedBox(
                                      width: 100,
                                      child: Column(
                                        children: [
                                          Text('Repeat', style: text),
                                          Transform.scale(
                                            scale: .8,
                                            child: CupertinoSwitch(
                                              value: visitorBloc.repeat,
                                              onChanged: (value) {
                                                visitorBloc.add(ToggleRepeatEvent());
                                              },
                                              applyTheme: true,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  if (visitorBloc.usageFrequencySelected ==
                                          'Periodic' &&
                                      visitorBloc.accessTypeSelected ==
                                          'Online Password')
                                    isRepeat
                                        ? const RepeatWidget()
                                        : const SizedBox(),
                                  Container(
                                    decoration: containerDecoration,
                                    width: size.width / 6,
                                    child: DefaultButton(
                                      onPressed: () {
                                        showDialog(
                                          context: context,
                                          barrierDismissible: false,
                                          builder: (BuildContext context) {
                                            return AddDeviceDialog(
                                              selectedDeviceIds:
                                                  visitorBloc.selectedDevices,
                                            );
                                          },
                                        ).then((listDevice) {
                                          if (listDevice != null) {
                                            visitorBloc.selectedDevices = listDevice;
                                          }
                                        });
                                      },
                                      borderRadius: 8,
                                      child: Text(
                                        '+ Add Device',
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(
                                                fontWeight: FontWeight.w400,
                                                color: ColorsManager.whiteColors,
                                                fontSize: 12),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
              actionsAlignment: MainAxisAlignment.center,
              actions: <Widget>[
                Container(
                  decoration: containerDecoration,
                  width: size.width * 0.2,
                  child: DefaultButton(
                    borderRadius: 8,
                    onPressed: () {
                      Navigator.of(context).pop(null);
                    },
                    backgroundColor: Colors.white,
                    child: Text(
                      'Cancel',
                      style: Theme.of(context).textTheme.bodySmall!.copyWith(
                          fontWeight: FontWeight.w400,
                          color: ColorsManager.blackColor,
                          fontSize: 16),
                    ),
                  ),
                ),
                Container(
                  decoration: containerDecoration,
                  width: size.width * 0.2,
                  child: DefaultButton(
                    onPressed: () {
                      if (visitorBloc.forgetFormKey.currentState!.validate()) {
                        if (visitorBloc.selectedDevices.isNotEmpty) {
                          if (visitorBloc.usageFrequencySelected == 'One-Time' &&
                              visitorBloc.accessTypeSelected == 'Offline Password') {
                            setPasswordFunction(context, size, visitorBloc);
                          } else if (visitorBloc.usageFrequencySelected ==
                                  'Periodic' &&
                              visitorBloc.accessTypeSelected == 'Offline Password') {
                            if (visitorBloc.expirationTime != 'End Time' &&
                                visitorBloc.effectiveTime != 'Start Time') {
                              setPasswordFunction(context, size, visitorBloc);
                            } else {
                              visitorBloc.stateDialog(
                                  context: context,
                                  message: 'Please select Access Period to continue',
                                  title: 'Access Period');
                            }
                          } else if (visitorBloc.endTimeAccess != 'End Time' &&
                              visitorBloc.startTimeAccess != 'Start Time') {
                            if (visitorBloc.effectiveTimeTimeStamp != null &&
                                visitorBloc.expirationTimeTimeStamp != null) {
                              if (isRepeat == true) {
                                if (visitorBloc.expirationTime != 'End Time' &&
                                    visitorBloc.effectiveTime != 'Start Time' &&
                                    visitorBloc.selectedDays.isNotEmpty) {
                                  setPasswordFunction(context, size, visitorBloc);
                                } else {
                                  visitorBloc.stateDialog(
                                      context: context,
                                      message:
                                          'Please select days and fill start time and end time to continue',
                                      title: 'Access Period');
                                }
                              } else {
                                setPasswordFunction(context, size, visitorBloc);
                              }
                            } else {
                              visitorBloc.stateDialog(
                                  context: context,
                                  message: 'Please select Access Period to continue',
                                  title: 'Access Period');
                            }
                          } else {
                            visitorBloc.stateDialog(
                                context: context,
                                message: 'Please select Access Period to continue',
                                title: 'Access Period');
                          }
                        } else {
                          visitorBloc.stateDialog(
                              context: context,
                              message: 'Please select devices to continue',
                              title: 'Select Devices');
                        }
                      }
                    },
                    borderRadius: 8,
                    child: Text(
                      'Ok',
                      style: Theme.of(context).textTheme.bodySmall!.copyWith(
                          fontWeight: FontWeight.w400,
                          color: ColorsManager.whiteColors,
                          fontSize: 16),
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Future<void> setPasswordFunction(
    BuildContext context,
    Size size,
    VisitorPasswordBloc visitorBloc,
  ) {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return BlocBuilder<VisitorPasswordBloc, VisitorPasswordState>(
          builder: (context, state) {
            if (state is LoadingInitialState) {
              // Show loading indicator while loading
              return AlertDialog(
                alignment: Alignment.center,
                content: SizedBox(
                  height: size.height * 0.25,
                  child: const Center(
                    child: CircularProgressIndicator(), // Display a loading spinner
                  ),
                ),
              );
            } else {
              return AlertDialog(
                alignment: Alignment.center,
                backgroundColor: Colors.white,
                content: SizedBox(
                  height: size.height * 0.13,
                  child: Column(
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(
                            child: SvgPicture.asset(
                              Assets.deviceNoteIcon,
                              height: 35,
                              width: 35,
                            ),
                          ),
                          const SizedBox(
                            height: 20,
                          ),
                          Text(
                            'Set Password',
                            style: Theme.of(context)
                                .textTheme
                                .headlineLarge!
                                .copyWith(
                                  fontSize: 24,
                                  fontWeight: FontWeight.w400,
                                  color: Colors.black,
                                ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 15),
                    ],
                  ),
                ),
                actionsAlignment: MainAxisAlignment.center,
                actions: <Widget>[
                  Container(
                    decoration: containerDecoration,
                    width: size.width * 0.1,
                    child: DefaultButton(
                      borderRadius: 8,
                      onPressed: () {
                        Navigator.of(context).pop(null);
                      },
                      backgroundColor: Colors.white,
                      child: Text(
                        'Cancel',
                        style: Theme.of(context).textTheme.bodySmall!.copyWith(
                              fontWeight: FontWeight.w400,
                              color: ColorsManager.blackColor,
                              fontSize: 16,
                            ),
                      ),
                    ),
                  ),
                  Container(
                    decoration: containerDecoration,
                    width: size.width * 0.1,
                    child: DefaultButton(
                      backgroundColor: Color(0xff023DFE),
                      borderRadius: 8,
                      onPressed: () {
                        Navigator.pop(context);
                        if (visitorBloc.usageFrequencySelected == 'One-Time' &&
                            visitorBloc.accessTypeSelected == 'Online Password') {
                          visitorBloc.add(OnlineOneTimePasswordEvent(
                            context: context,
                            passwordName: visitorBloc.userNameController.text,
                            email: visitorBloc.emailController.text,
                          ));
                        } else if (visitorBloc.usageFrequencySelected ==
                                'Periodic' &&
                            visitorBloc.accessTypeSelected == 'Online Password') {
                          visitorBloc.add(OnlineMultipleTimePasswordEvent(
                            passwordName: visitorBloc.userNameController.text,
                            email: visitorBloc.emailController.text,
                            effectiveTime:
                                visitorBloc.effectiveTimeTimeStamp.toString(),
                            invalidTime:
                                visitorBloc.expirationTimeTimeStamp.toString(),
                          ));
                        } else if (visitorBloc.usageFrequencySelected ==
                                'One-Time' &&
                            visitorBloc.accessTypeSelected == 'Offline Password') {
                          visitorBloc.add(OfflineOneTimePasswordEvent(
                            context: context,
                            passwordName: visitorBloc.userNameController.text,
                            email: visitorBloc.emailController.text,
                          ));
                        } else if (visitorBloc.usageFrequencySelected ==
                                'Periodic' &&
                            visitorBloc.accessTypeSelected == 'Offline Password') {
                          visitorBloc.add(OfflineMultipleTimePasswordEvent(
                            passwordName: visitorBloc.userNameController.text,
                            email: visitorBloc.emailController.text,
                            effectiveTime:
                                visitorBloc.effectiveTimeTimeStamp.toString(),
                            invalidTime:
                                visitorBloc.expirationTimeTimeStamp.toString(),
                          ));
                        }
                      },
                      child: Text(
                        'Confirm',
                        style: Theme.of(context).textTheme.bodySmall!.copyWith(
                              fontWeight: FontWeight.w400,
                              color: ColorsManager.whiteColors,
                              fontSize: 16,
                            ),
                      ),
                    ),
                  ),
                ],
              );
            }
          },
        );
      },
    );
  }
}
