import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:tanami_app/core/styles/app_color.dart';
import 'package:tanami_app/core/styles/app_text.dart';
import 'package:tanami_app/features/countrySelection/bloc/choose_country_bloc.dart';
import 'package:tanami_app/features/securePin/presentation/widgets/forgot_pin_dialog.dart';
import 'package:tanami_app/shared/components/text_widget.dart';

import '../../../../core/routes/route_name.dart';
import '../../../../core/routes/routes.dart';
import '../../../../core/utils/language/localizations_delegate.dart';
import '../../../../shared/components/loader.dart';
import '../../../../shared/components/toast_message.dart';
import '../../../login/presentation/bloc/login_bloc.dart';
import '../bloc/pin_bloc.dart';

class PinKey extends StatelessWidget {
  final String fromScreen;
  const PinKey({
    super.key,
    required this.fromScreen,
  });

  @override
  Widget build(BuildContext context) {
    var localizations = AppLocalizations.of(context);
    final loginBloc = context.read<LoginBloc>();
    final radioBloc = context.read<RadioBloc>();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const Gap(20),
        BlocConsumer<PinBloc, PinState>(
          listener: (context, state) {
            if (state is PinLoading) {
              Loader.loader(context);
            }
            if (state.pinComplete &&
                state.error.isEmpty &&
                !state.verifiedOnce) {
              if (fromScreen == "login" || fromScreen == "LoginedInUser") {
                goRouter.pop();
                loginBloc.resetFields();
                radioBloc.resetSelection();
                successToastMessage(context,
                    localizations.translate(AppText.pinVerifiedSucess));
                goRouter.pushNamed(RouteName.mainScreen);
              } else if (fromScreen == "reset-pin") {
                successToastMessage(
                    context, localizations.translate(AppText.pinUpdatedSucess));
                goRouter.pop();
                goRouter.pop();
              } else {
                goRouter.pop();
                context.read<PinBloc>().add(SavePinPressed());
                goRouter.pushNamed(RouteName.confirmPinScreen);
              }
            } else {
              // goRouter.pop();
              if (state.pinComplete) {
                errorToastMessage(
                  context,
                  state.error,
                );
              }
            }
          },
          builder: (context, state) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(6, (index) {
                return Container(
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: index < state.pin.length
                          ? AppColor.pinFillBorderColor
                          : AppColor.pinInActiveBorderColor,
                    ),
                    color: index < state.pin.length
                        ? AppColor.pinFillColor
                        : Colors.transparent,
                  ),
                );
              }),
            );
          },
        ),
        (fromScreen == "login" ||
                fromScreen == "forgot-pin" ||
                fromScreen == "LoginedInUser")
            ? const Gap(20)
            : const Gap(0),
        (fromScreen == "login" || fromScreen == "LoginedInUser")
            ? GestureDetector(
                onTap: () {
                  forgotPinDialog(context);
                },
                child: Padding(
                  padding: const EdgeInsets.only(
                    right: 50,
                  ),
                  child: TextWidget().text15W500(
                    localizations.translate(AppText.forgotPinCode),
                    clr: AppColor.hintTextColor,
                    textDecoration: TextDecoration.underline,
                  ),
                ),
              )
            : const SizedBox(),
        const Gap(20),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 1.3,
          ),
          itemCount: 12,
          itemBuilder: (context, index) {
            if (index == 9) {
              return const SizedBox.shrink();
            } else if (index == 11) {
              return GestureDetector(
                onTap: () {
                  context.read<PinBloc>().add(BackspacePressed());
                },
                child: Container(
                  margin: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black12),
                  ),
                  child: const Icon(
                    Icons.arrow_back_rounded,
                  ),
                ),
              );
            } else {
              final number = index == 10 ? '0' : '${index + 1}';
              return GestureDetector(
                onTap: () {
                  context
                      .read<PinBloc>()
                      .add(NumberPressed(number, fromScreen));
                },
                child: Container(
                  margin: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black12),
                  ),
                  child: Center(
                      child: TextWidget().text20W700(
                    number,
                    clr: AppColor.plainBlack,
                  )),
                ),
              );
            }
          },
        ),
      ],
    );
  }
}
