// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/screens/auth/state/state.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/utils/timer/apt_simple_timer_with_controller.dart';
import 'package:qadirneyriz/utils/tools/tools.dart';
import 'package:qadirneyriz/widgets/otp_textfield.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class OtpScreen extends StatefulWidget {
  final String phoneNumber;
  const OtpScreen({
    super.key,
    required this.phoneNumber,
  });

  @override
  State<OtpScreen> createState() => _OtpScreenState();
}

class _OtpScreenState extends State<OtpScreen> {
  bool timerEnd = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<AuthState>(
        builder: (context, value, child) {
          return CustomScrollView(
            slivers: <Widget>[
              SliverToBoxAdapter(
                child: Container(
                  height: 30,
                  color: config.ui.mainGreen,
                ),
              ),
              // Header Image with cut-out shape at the bottom
              SliverToBoxAdapter(
                child: ClipPath(
                  child: Image.asset(
                    'assets/images/template.png',
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SliverPadding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                sliver: SliverToBoxAdapter(
                  child: Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color:
                                Colors.black.withOpacity(0.1), // light shadow
                            blurRadius: 10,
                            spreadRadius: 5,
                          ),
                        ],
                      ),
                      child: Column(
                        children: [
                          Text(
                            AppLocalizations.of(context)!.enterotp,
                            style: TextStyle(
                                color: config.ui.mainGray,
                                fontSize: 18,
                                fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(
                            height: 5,
                          ),
                          Text(
                            AppLocalizations.of(context)!.an4digitotp,
                            style: TextStyle(
                              color: config.ui.mainGray.withOpacity(.5),
                              fontSize: 14,
                            ),
                          ),
                          const SizedBox(
                            height: 5,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                widget.phoneNumber,
                                style: TextStyle(
                                    color: config.ui.mainGray.withOpacity(.5),
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold),
                              ),
                              Icon(
                                Icons.phone_callback_outlined,
                                color: config.ui.mainGreen,
                              )
                            ],
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          OTPTextField(
                              length: 4,
                              onSubmitted: (onSubmitted) {
                                otpCheckCode(onSubmitted, value);
                              }),
                          const SizedBox(
                            height: 20,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              resendOtpbutton(value),
                              if (!timerEnd)
                                Directionality(
                                  textDirection: TextDirection.ltr,
                                  child: AptSimpleTimerWithController(
                                    seconds: 60,
                                    fontSize: 16,
                                    timerColor: const Color(0xff8FA5B6)
                                        .withOpacity(0.6),
                                    onTimerEnd: () {
                                      setState(() {
                                        timerEnd = true;
                                      });
                                    },
                                  ),
                                ),
                            ],
                          ),
                        ],
                      )),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget resendOtpbutton(AuthState value) {
    return timerEnd
        ? GestureDetector(
            onTap: value.statusSendotp != Status.loading
                ? () async {
                    final status = await value.sendOtp(
                      mobile: widget.phoneNumber,
                    );
                    if (status == Status.ready) {
                      setState(() {
                        timerEnd = false;
                      });
                    } else {
                      Tools.showCustomSnackBar(
                        text: value.errorsSendOtp == null
                            ? value.messageSendOtp ?? 'An error has occurred'
                            : Tools.combineErrorMessages(
                                value.errorsSendOtp ?? {}),
                        isError: true,
                        context,
                      );
                    }
                  }
                : null,
            child: Text(
              value.statusSendotp == Status.loading
                  ? AppLocalizations.of(context)!.loading
                  : AppLocalizations.of(context)!.resend,
              style: TextStyle(
                color: config.ui.secendGreen,
                fontSize: 16,
              ),
            ),
          )
        : Container();
  }

  void otpCheckCode(onSubmitted, AuthState value) async {
    if (onSubmitted.length == 4) {
      final status =
          await value.login(mobile: widget.phoneNumber, otp: onSubmitted);
      if (status == Status.ready) {
        context.goNamed('navigate', pathParameters: {'tab': '0'});
      } else if (status == Status.error) {
        Tools.showCustomSnackBar(
          text: value.errorsLogin == null
              ? value.messageLogin ?? AppLocalizations.of(context)!.haserror
              : Tools.combineErrorMessages(value.errorsLogin ?? {}),
          isError: true,
          context,
        );
        setState(() {});
      } else if (status == Status.empty) {
        Tools.showCustomSnackBar(
          text: value.errorsLogin == null
              ? value.messageLogin ?? AppLocalizations.of(context)!.haserror
              : Tools.combineErrorMessages(value.errorsLogin ?? {}),
          isError: true,
          context,
        );
        onSubmitted = '';
      }
    }
  }
}
