
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/localization/localization.dart';
import 'package:top_news_app/repos/exception_handlers.dart';
import 'package:top_news_app/screen/reset_password.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:top_news_app/services/auth_service.dart';


class EmailLoginScreen extends StatefulWidget {
  const EmailLoginScreen({super.key});

  @override
  State<EmailLoginScreen> createState() => _EmailLoginScreenState();
}

class _EmailLoginScreenState extends State<EmailLoginScreen> {

  final email = TextEditingController();
  final password = TextEditingController();
  final AuthService _authService = AuthService();
  bool _passwordVisible = true;

   bool _isLoading = false;


  login(context) async {
    try{

      setState(() {
        _isLoading = true;
      });

      await _authService.login(context, email.text, password.text);
      setState(() {
        _isLoading = false;
      });
    }catch(e){
      var message = ExceptionHandlers().getExceptionString(e);

      throw message;
    }

    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          leading: Container(),
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          elevation: 0,
          actions: [IconButton(icon: Icon(Icons.cancel_outlined,
            color: Theme.of(context).iconTheme.color,), onPressed: (){
            Navigator.pushReplacementNamed(context, '/main-screen');
          })],
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
           mainAxisAlignment: MainAxisAlignment.center,
            children: [
              customSizeBox(30),
              ConstrainedBox(
                constraints: BoxConstraints(
                    maxWidth: size.width / 2.2, maxHeight: 140),
                child: Container(
                  decoration:  BoxDecoration(
                    image:
                    DecorationImage(image: Theme.of(context).brightness == Brightness.dark ?   AssetImage(darkLogo) :  AssetImage(lightLogo)),
                  ),
                ),
              ),
              Text(
                getTranslated(context, 'Sign In') ?? 'Sign In',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontFamily: fontFamily,
                    fontSize: 24),
                textAlign: TextAlign.center,
              ),
              customSizeBox(5),
              Text(
                getTranslated(context, 'Follow the simple steps') ?? 'Follow the simple steps',
                style: TextStyle(
                    fontWeight: FontWeight.normal,
                    fontFamily: fontFamily,
                    fontSize: 14),
                textAlign: TextAlign.center,
              ),
              customSizeBox(80),
              TextField(
                decoration:  InputDecoration(
                  labelText: getTranslated(context, 'Enter Email') ?? 'Enter Email',
                  contentPadding: const EdgeInsets.symmetric(vertical: 12.0),
                  focusedBorder: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey, width: 1),
                  ),
                  enabledBorder: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey, width: 1),
                  ),
                  filled: true,
                  prefixIcon: const Icon(
                    Icons.email,
                  ),
                ),
                keyboardType: TextInputType.emailAddress,
                controller: email,
              ),
              customSizeBox(20),
              TextField(
                obscureText: _passwordVisible,
                decoration: InputDecoration(
                  labelText: getTranslated(context, 'Password') ?? 'Password',
                  contentPadding: const EdgeInsets.symmetric(vertical: 12.0),
                  focusedBorder: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey, width: 1),
                  ),
                  enabledBorder: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey, width: 1),
                  ),
                  filled: true,
                  prefixIcon: const Icon(
                    Icons.lock,
                  ),
                  suffixIcon: IconButton(
                    icon: Icon(
                      !_passwordVisible
                          ? Icons.visibility
                          : Icons.visibility_off,
                      color: Colors.grey,
                    ),
                    onPressed: () {
                      setState(() {
                        _passwordVisible = !_passwordVisible;
                      });
                    },
                  ),
                ),
                keyboardType: TextInputType.text,
                controller: password,
              ),
              Container(
                padding: const EdgeInsets.only(top: 20, bottom: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context)=> const ResetPassword()));
                      },
                      child: Text(
                        '${getTranslated(context, 'Forget Password') ?? 'Forget Password'} ?',
                        style: GoogleFonts.robotoSerif(
                          color: Theme.of(context).iconTheme.color,
                          fontSize:14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () {
                  login(context);
                },
                child: Container(
                    height: 45,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5.0),
                      color: primaryColorsAccent,
                    ),
                    child: _isLoading == false
                        ?  Center(
                            child: Text(
                            getTranslated(context, 'Sign In') ?? 'Sign In',
                            style: buttonTextStyle,
                          ))
                        :  Center(
                            child: Text(
                            '${getTranslated(context, 'Processing') ?? 'Processing'}....',
                            style: buttonTextStyle,
                          ))),
              ),
              const SizedBox(
                height: 20,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '${getTranslated(context, 'Create New Account') ?? 'Create New Account'}!',
                    style: GoogleFonts.robotoSerif(
                      fontSize: 14,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pushReplacementNamed(context, '/sign-up');
                    },
                    child: Text(
                      '  ${getTranslated(context, 'Register') ?? 'Register'}',
                      style: GoogleFonts.robotoSerif(
                        fontSize: 14,
                        color: primaryColors
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
