import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:garage/user/model/car_user.dart';
import 'package:garage/user/service/user_service.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';

import '../../home_page.dart';
import '../../user/model/user_provider.dart';

class LoginPage extends StatelessWidget {
  final UserService userService = GetIt.instance<UserService>();

  LoginPage({super.key});

  Duration get loginTime => const Duration(milliseconds: 25);

  Future<String?> _loginUser(LoginData data, UserProvider provider) async {
    late final UserCredential credentials;

    try {
      credentials = await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: data.name, password: data.password);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        return 'No user found for that email.';
      }
      if (e.code == 'wrong-password') {
        return 'Wrong password provided for that user.';
      }
      print(e.code);
      return "Authentication error";
    }
    final String? fcmToken = await FirebaseMessaging.instance.getToken();

    userService
        .getItemById(credentials.user!.uid)
        .then((value) => provider.setAndAddToken(value!, fcmToken));
    return null;
  }

  static void logoutUser() {
    FirebaseAuth.instance.signOut();
  }

  Future<String?> _signupUser(SignupData data, UserProvider provider) async {
    late final UserCredential credentials;
    try {
      credentials = await FirebaseAuth.instance.createUserWithEmailAndPassword(
          email: data.name!, password: data.password!);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'email-already-in-use') {
        return 'This email is already connected to an account.';
      }
      if (e.code == 'invalid-email') {
        return 'This email is not valid.';
      }
      if (e.code == 'weak-password') {
        return 'Your password is too weak.';
      }
      print(e.code);
      return "Authentication error";
    }
    final String? fcmToken = await FirebaseMessaging.instance.getToken();
    CarUser user = CarUser(
      id: credentials.user!.uid,
      name: "Useless",
      email: credentials.user!.email!,
      cars: [],
      archivedCars: {},
      fcmTokens: fcmToken == null ? {} : {fcmToken},
      licenceExpiration: null,
    );
    userService.createItemWithId(user, credentials.user!.uid);

    provider.currentUser = user;
    return null;
  }

  Future<String> _recoverPassword(String name) {
    return Future.delayed(loginTime).then((_) {
      return 'Not implemented';
    });
  }

  @override
  Widget build(BuildContext context) {
    return FlutterLogin(
      title: 'Moje garáž',
      logo: const AssetImage('images/logo_garage_removed.png'),
      onLogin: (login) {
        return _loginUser(login, context.read<UserProvider>());
      },
      onSignup: (login) {
        return _signupUser(login, context.read<UserProvider>());
      },
      onSubmitAnimationCompleted: () {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => const HomePage(),
        ));
      },
      onRecoverPassword: _recoverPassword,
      theme: LoginTheme(
          primaryColor: Theme.of(context).colorScheme.secondary,
          accentColor: Theme.of(context).colorScheme.secondary,
          pageColorLight: Theme.of(context).colorScheme.primaryContainer,
          titleStyle: TextStyle(fontWeight: FontWeight.bold),
          buttonStyle: TextStyle(color: Colors.white)),
      loginProviders: const [
        // LoginProvider(
        //   icon: Icons.g_mobiledata,
        //   label: 'Google',
        //   callback: () async {
        //     debugPrint('start google sign in');
        //     await Future.delayed(loginTime);
        //     debugPrint('stop google sign in');
        //     return "Not implemented";
        //   },
        // ),
      ],
    );
  }
}
