import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';

import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:gifunavi/model/auth_user.dart';
import 'package:gifunavi/nrog/pages/home_page.dart';
import 'package:gifunavi/provider/auth_provider.dart';
import 'package:gifunavi/services/auth_service.dart';
import 'package:gifunavi/widgets/c_form_text_field.dart';
import 'package:gifunavi/widgets/c_password_text_filed.dart';

class AuthPage extends ConsumerStatefulWidget {
  const AuthPage({super.key});

  @override
  ConsumerState<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends ConsumerState<AuthPage> {
  final _formkey = GlobalKey<FormState>();
  final FocusNode focusEmail = FocusNode();
  final FocusNode focusPwd = FocusNode();
  var _authMode = 'login';
  bool _isLoginProgress = false;

  final TextEditingController _emailTextEditingController =
      TextEditingController();
  final TextEditingController _passwordTextEditingController =
      TextEditingController();

  @override
  void initState() {
    super.initState();
    _emailTextEditingController.addListener(() => setState(() {}));
    WidgetsBinding.instance.addPostFrameCallback((_) {
      checkUser();
    });
  }

  void _submit() async {
    setState(() {
      _isLoginProgress = true;
    });
    if (_formkey.currentState!.validate()) {
      AuthService authService = AuthService();
      AuthUser? user = await authService.userLogin(
          _emailTextEditingController.text,
          _passwordTextEditingController.text);
      if (user != null) {
        setState(() {
          ref.read(authUserStateProvider.notifier).addLogin(user);
        });
      }
    }
    setState(() {
      _isLoginProgress = false;
    });
  }

  Future<void> _submitToken(String token) async {
    setState(() {
      _isLoginProgress = true;
    });
    AuthService authService = AuthService();
    AuthUser? user = await authService.userFromToken(token);
    //////////////print("---user is ${user} ---");
    if (user != null) {
      setState(() {
        _isLoginProgress = false;
        ref.read(authUserStateProvider.notifier).addLogin(user);
      });
    } else {}
  }

  void checkUser() async {
    String? token =
        await ref.read(authUserStateProvider.notifier).tokenFromDevice();
    //////////////print("--- red token is ${token} ---");
    await _submitToken(token!);
    final id = ref.read(authUserStateProvider).id;
    if (id != null) {
      if (context.mounted) {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (ctx) => const HomePage()));
      }
    }
      return;
  }

  @override
  Widget build(BuildContext context) {
    if (ref.read(authUserStateProvider).id != null) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (ctx) => const HomePage()));
    }

    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: KeyboardDismisser(
        gestures: const [
          GestureType.onTap,
          //GestureType.onVerticalDragDown
        ],
        child: Center(
            child: SizedBox(
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              buildAuthCard(),
              buildLogo(),
            ],
          ),
        )),
      ),
    );
  }

  Positioned buildLogo() {
    return Positioned(
      top: -170,
      left: MediaQuery.of(context).size.width / 2 - 100,
      child: Center(
        child: Container(
          alignment: Alignment.center,
          width: 200,
          height: 200,
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            image: DecorationImage(
                image: AssetImage('assets/images/appicon.png'),
                fit: BoxFit.fill),
          ),
        ),
      ),
    );
  }

  Widget buildAuthCard() {
    return Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Form(
            key: _formkey,
            child: Padding(
              padding: const EdgeInsets.only(
                  top: 40, bottom: 10, left: 12, right: 12),
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: CFormTextField(
                        cFocus: focusEmail,
                        cController: _emailTextEditingController),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10),
                    child: CPasswordTextField(
                      cController: _passwordTextEditingController,
                      cFocusNode: focusPwd,
                    ),
                  ),
                  const SizedBox(
                    height: 12,
                  ),
                  buildControlls(),
                  // SizedBox(height: MediaQuery.of(context).viewInsets.bottom,)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildControlls() {
    if (_isLoginProgress) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    final usr = ref.read(authUserStateProvider);
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Padding(
              padding: const EdgeInsets.only(right: 12.0),
              child: ElevatedButton(
                  onPressed: _submit,
                  child: Text(_authMode == "login" ? "Submit" : "Register",
                      style: GoogleFonts.lato(
                          color: Theme.of(context).colorScheme.secondary))),
            )
          ],
        ),
        TextButton(
          onPressed: () {
            setState(() {
              if (_authMode == 'login') {
                _authMode = 'register';
              } else {
                _authMode = 'login';
              }
            });
          },
          child: Text(
            _authMode == "login"
                ? "${usr.id} Dont have account, please Register"
                : "Already Registered, Login",
            style: GoogleFonts.lato(
                color: Theme.of(context).colorScheme.primary,
                decoration: TextDecoration.underline,
                fontSize: 16,
                fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }
}
