import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:initial_folder/providers/forgot_password_provider.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'success_screen.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:flutter/src/material/scaffold.dart';
import 'package:initial_folder/providers/reset_provider.dart';
import 'package:initial_folder/widgets/login_regist/custom_text_form_field.dart';

class ResetScreen extends StatefulWidget {
  static String routeName = "/reset";
  ResetScreen({Key? key, this.email = ''}) : super(key: key);
  final String email;
  

  @override
  State<ResetScreen> createState() => _ResetScreenState();
}

class _ResetScreenState extends State<ResetScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController emailController = TextEditingController();
  bool isLoading = false;
  

  void showRePaEr(Map<String, dynamic> error) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        surfaceTintColor: Colors.transparent,
        insetPadding: EdgeInsets.symmetric(horizontal: 25, vertical: 20),
        content: Container(
          alignment: AlignmentDirectional.bottomCenter,
          height: 50,
          child: Text(
            // error['messages']['error'] ?? '',
            "Terjadi kesalahan, gagal reset password",
            style: primaryTextStyle.copyWith(
                fontSize: getProportionateScreenWidth(12), letterSpacing: 1),
          ),
        ),
        actions: [
          Container(
            height: 30,
            alignment: AlignmentDirectional.topEnd,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text('Tutup',
                  style: primaryTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(12),
                      letterSpacing: 1,
                      color: primaryColor)),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final _resetProvider = Provider.of<ResetProvider>(context, listen: false);

    Future<void> _resetPassword() async {
   try {
      bool success = await _resetProvider.resetPassword(email: emailController.text);
      if (success) {
         Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ResetSuccess(email: emailController.text),
          ),
        );
      } else {
         showRePaEr({"message": "Gagal reset password, coba lagi."});
      }
      } catch (e) {
          print(e);
          showRePaEr({"message": "Terjadi kesalahan saat reset password."});
      }
      setState(() {
          isLoading = false;
      });
    }
    SizeConfig().init(context);

    Widget form() {
      Widget resetEmailInput() {
        return CustomTextField(
          pad: getProportionateScreenWidth(16),
          controler: emailController,
          hinttext: 'Masukkan email',
          title: 'Email',
          validate: validateEmail,
        );
      }

      Widget button() {
        if (isLoading) {
          return Padding(
            padding: EdgeInsets.symmetric(
              horizontal: getProportionateScreenWidth(60),
            ),
            child: const LoadingButton(
              backgroundButtonColor: primaryColor,
              textButtonColor: ninthColor,
            ),
          );
        } else {
          return Padding(
            padding: EdgeInsets.symmetric(
                horizontal: getProportionateScreenWidth(60)),
            child: DefaultButton(
              text: 'Reset password',
              press: () {
                if (_formKey.currentState!.validate()) {
                  setState(() {
                    isLoading = true;
                  });
                  _resetPassword();
                }
              },
            ),
          );
        }
      }

      return Form(
        key: _formKey,
        child: Column(
          children: [
            resetEmailInput(),
            button(),
          ],
        ),
      );
    }

    return SafeArea(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.background,
          centerTitle: true,
          title: Text(
            'Reset Password',
            style: thirdTextStyle.copyWith(
              fontWeight: bold,
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: getProportionateScreenHeight(15),
              ),
              Container(
                  child: Padding(
                padding: EdgeInsets.all(getProportionateScreenWidth(12)),
                child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      'Masukkan email yang terhubung ke akunmu dan kami akan mengirimkan link untuk mereset password',
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(12),
                      ),
                      textAlign: TextAlign.justify,
                    )),
              )),
              SizedBox(
                height: getProportionateScreenHeight(32),
              ),
              form(),
              SizedBox(height: getProportionateScreenHeight(32)),
              SizedBox(height: getProportionateScreenHeight(32)),
            ],
          ),
        ),
      ),
    );
  }
}
