import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:gap/gap.dart';
import 'package:pharmacy_mobile/auth/auth_service.dart';
import 'package:pharmacy_mobile/widgets/button_widget.dart';
import 'package:pharmacy_mobile/widgets/input_widget.dart';
import 'package:pharmacy_mobile/widgets/logo_widget.dart';
import 'package:pharmacy_mobile/widgets/page_background_widget.dart';
import 'package:pharmacy_mobile/widgets/snackbar_widget.dart';
import 'package:pharmacy_mobile/widgets/text_widget.dart';
import 'package:pharmacy_mobile/widgets/title_widget.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _authService = AuthService();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  bool _isLoading = false;

  void _signIn() async {
    // if (_isLoading) return;

    final email = _emailController.text;
    final password = _passwordController.text;

    if (email.isEmpty) {
      if (mounted) {
        showNotification(context, 'Error: Please enter a valid email', false);
      }
      return;
    }

    if (password.isEmpty) {
      if (mounted) {
        showNotification(context, 'Error: Please enter a password', false);
      }
      return;
    }

    setState(() => _isLoading = true);

    try {
      if (await InternetConnectionChecker.instance.hasConnection) {
        await _authService.signIn(email, password);

        if (mounted) {
          final user = _authService.getCurrentUser();

          if (user != null) {
            showNotification(context, 'Login Successful', true);

            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (user.contains('admin')) {
                if (mounted) context.push('/main');
              } else {
                if (mounted) context.push('/customer');
              }
            });
          }
        }
      } else {
        if (mounted) {
          showNotification(context, 'Error: No Internet Connection', false);
        }
      }
    } catch (e) {
      if (e is AuthException) {
        final errorMessage = e.message;

        if (mounted) {
          // showNotification(context, 'Error: $errorMessage', false);
          if (errorMessage == 'Invalid login credentials') {
            showNotification(context, 'Error: Invalid Email or Password', false);
          }
        }
      }
    } finally {
      setState(() => _isLoading = false);
    }

    // if (mounted) {
    //   context.showSnackBar('Check your email for a login link!');

    //   _emailController.clear();
    // }
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: PageBackgroundWidget(
          page: 'login',
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Gap(96),
                const TitleWidget(
                  firstTextSize: 14,
                  secondTextSize: 24,
                  logoSize: 90,
                ),
                const Gap(32),
                const TextWidget(
                  text: 'Login',
                  title: true,
                ),
                const Gap(16),
                Padding(
                  padding: const EdgeInsets.only(left: 32, right: 32),
                  child: Container(
                    padding: const EdgeInsets.fromLTRB(32, 32, 32, 40),
                    decoration: const BoxDecoration(
                        color: Color.fromRGBO(57, 38, 62, 0.6),
                        borderRadius: BorderRadius.all(Radius.circular(16)),
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromRGBO(0, 0, 0, 0.2), // Subtle shadow to give depth
                            spreadRadius: 0,
                            blurRadius: 4,
                            offset: Offset(0, 2),
                          )
                        ]),
                    child: Form(
                        child: Column(
                      children: [
                        InputWidget(label: 'Email', controller: _emailController),
                        const Gap(16),
                        KeyboardListener(
                          focusNode: _focusNode,
                          onKeyEvent: (event) {
                            if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.enter) {
                              _signIn();
                            }
                          },
                          child: InputWidget(
                            label: 'Password',
                            controller: _passwordController,
                            password: true,
                          ),
                        ),
                        const Gap(40),
                        // TextButton(onPressed: () => {_signIn()}, child: const Text('Login'))
                        if (_isLoading)
                          const Center(child: CircularProgressIndicator(color: Color.fromRGBO(255, 255, 255, 1)))
                        else
                          ButtonWidget(text: 'Login', onPressed: _signIn)
                      ],
                    )),
                  ),
                ),
                const Gap(16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const TextWidget(
                      text: "Don't have an account?",
                      size: 14,
                    ),
                    const Gap(8),
                    GestureDetector(
                      onTap: () => {context.push('/register')},
                      child: const TextWidget(
                        text: 'Register here',
                        size: 14,
                        underlined: true,
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        ));
  }
}
