import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_event.dart';
import 'package:syncrow_app/features/devices/bloc/smart_door_bloc/smart_door_state.dart';
import 'package:syncrow_app/features/devices/view/widgets/name_time_widget.dart';
import 'package:syncrow_app/features/devices/view/widgets/smart_door/repeat_widget.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';

class CreateTemporaryPassword extends StatelessWidget {
  final String? deviceId;
  final String? type;
  const CreateTemporaryPassword({super.key, this.deviceId, this.type});
  @override
  Widget build(BuildContext context) {
    bool isRepeat = false;
    // bool generated = false;
    return BlocProvider(
        create: (BuildContext context) => SmartDoorBloc(deviceId: deviceId!),
        child: BlocConsumer<SmartDoorBloc, SmartDoorState>(listener: (context, state) {
          if (state is FailedState) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.errorMessage),
                backgroundColor: Colors.red,
              ),
            );
          }
          if (state is IsRepeatState) {
            isRepeat = state.repeat;
          }
          if (state is GeneratePasswordOneTimestate) {
            // generated = state.generated;
          }
        }, builder: (context, state) {
          final smartDoorBloc = BlocProvider.of<SmartDoorBloc>(context);
          return DefaultScaffold(
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              centerTitle: true,
              title: const BodyLarge(
                text: 'Create Password',
                fontColor: ColorsManager.primaryColor,
                fontWeight: FontsManager.bold,
              ),
              leading: IconButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  icon: const Icon(Icons.arrow_back)),
              actions: type == 'Online Password'
                  ? [
                      TextButton(
                          onPressed: () {
                            smartDoorBloc.add(SavePasswordEvent(context: context));
                          },
                          child: const Text('Save'))
                    ]
                  : null,
            ),
            child: state is LoadingInitialState
                ? const Center(child: CircularProgressIndicator())
                : SingleChildScrollView(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const BodyMedium(
                          text:
                              'Save the password immediately. The password is not displayed in the app.',
                          fontWeight: FontWeight.normal,
                          fontColor: ColorsManager.grayColor,
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        const BodyMedium(
                          text: '7-Digit Password',
                          fontWeight: FontWeight.normal,
                          fontColor: ColorsManager.grayColor,
                        ),
                        DefaultContainer(
                          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                          child: Padding(
                            padding: EdgeInsets.symmetric(
                                horizontal: type == 'Online Password' ? 0 : 25),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                Flexible(
                                    flex: 2,
                                    child: PinCodeTextField(
                                      onCompleted: (value) {
                                        if (value.split('').every((char) => char == '1')) {
                                          smartDoorBloc.passwordController.clear();
                                          CustomSnackBar.displaySnackBar(
                                              'All characters cannot be 1.');
                                        }
                                      },
                                      autoDisposeControllers: false,
                                      keyboardType: TextInputType.phone,
                                      length: 7,
                                      // enabled:type == 'Online Password'? true:false,
                                      obscureText: false,
                                      animationType: AnimationType.fade,
                                      pinTheme: PinTheme(
                                          shape: PinCodeFieldShape.underline,
                                          fieldHeight: 45,
                                          fieldWidth: 20,
                                          activeFillColor: Colors.white,
                                          disabledColor: Colors.grey,
                                          activeColor: Colors.grey,
                                          errorBorderColor: Colors.grey,
                                          inactiveColor: Colors.grey,
                                          inactiveFillColor: Colors.grey,
                                          selectedColor: Colors.grey),
                                      animationDuration: const Duration(milliseconds: 300),
                                      backgroundColor: Colors.white,
                                      enableActiveFill: false,
                                      controller: smartDoorBloc.passwordController,
                                      appContext: context,
                                    )),
                                const SizedBox(
                                  width: 10,
                                ),
                                if (type == 'Online Password')
                                  Flexible(
                                    child: InkWell(
                                        onTap: () {
                                          smartDoorBloc.add(GeneratePasswordEvent());
                                        },
                                        child: const BodyMedium(
                                          text: 'Generate Randomly',
                                          fontWeight: FontWeight.bold,
                                          fontColor: ColorsManager.primaryColor,
                                        )),
                                  )
                              ],
                            ),
                          ),
                        ),
                        if (smartDoorBloc.passwordController.text.isNotEmpty)
                          TextButton(
                              onPressed: () async {
                                await Clipboard.setData(
                                    ClipboardData(text: smartDoorBloc.passwordController.text));
                              },
                              child: const Text('Copy')),
                        const SizedBox(
                          height: 20,
                        ),
                        NameTimeWidget(),
                        const SizedBox(
                          height: 20,
                        ),
                        DefaultContainer(
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                          child: ListTile(
                            contentPadding: EdgeInsets.zero,
                            leading: const BodyMedium(
                              text: 'Repeat',
                              fontWeight: FontWeight.normal,
                            ),
                            trailing: Transform.scale(
                                scale: .8,
                                child: CupertinoSwitch(
                                  value: smartDoorBloc.repeat,
                                  onChanged: (value) {
                                    smartDoorBloc.add(ToggleRepeatEvent());
                                  },
                                  applyTheme: true,
                                )),
                          ),
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        isRepeat ? const RepeatWidget() : const SizedBox(),
                        const SizedBox(
                          height: 40,
                        )
                      ],
                    ),
                  ),
          );
        }));
  }
}
