import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:smart_hotel_app/blocs/auth/auth_bloc.dart';
import 'package:smart_hotel_app/blocs/auth/auth_state.dart';
import 'package:smart_hotel_app/utils/storage/storage_service.dart';
import 'package:smart_hotel_app/views/login/cubit/login_cubit.dart';
import 'package:smart_hotel_app/views/login/cubit/login_state.dart';
import 'package:smart_hotel_app/views/login/widget/btn_login.dart';
import 'package:smart_hotel_app/views/login/widget/password_field.dart';
import 'package:smart_hotel_app/views/login/widget/remember_password_row.dart';
import 'package:smart_hotel_app/views/login/widget/username_field.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class LoginView extends StatelessWidget {
  LoginView({super.key});

  final _frmGlobalKey = GlobalKey<FormState>();
  final _txtUserNameController = TextEditingController();
  final _txtPwdController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
    );

    return BlocProvider(
      create: (_) {
        final cubit = LoginCubit(
          authBloc: context.read<AuthBloc>(),
          storageService: StorageService(),
        );
        cubit.loadRememberCredentials();
        return cubit;
      },
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
          statusBarBrightness: Brightness.light,
        ),
        child: Scaffold(
          backgroundColor: const Color(0xFFF5F7FA),
          resizeToAvoidBottomInset: true,
          body: SafeArea(
            top: false,
            child: Container(
              width: double.infinity,
              height: double.infinity,
              padding: EdgeInsets.only(left: 50.w, right: 50.w),
              decoration: const BoxDecoration(
                color: Color(0xFFF5F7FA),
              ),
              child: SingleChildScrollView(
                child: BlocBuilder<LoginCubit, LoginState>(
                  builder: (context, state) {
                    final cubit = context.read<LoginCubit>();

                    if (state.savedUsername != null) {
                      _txtUserNameController.text = state.savedUsername!;
                    }
                    if (state.savedPassword != null) {
                      _txtPwdController.text = state.savedPassword!;
                    }

                    return Column(
                      children: [
                        SizedBox(height: 150.h),
                        Container(
                          margin: EdgeInsets.only(bottom: 80.h),
                          child: Column(
                            children: [
                              Container(
                                width: 160.w,
                                height: 160.w,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(40.w),
                                  gradient: const LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      Color(0xFF00C6FF),
                                      Color(0xFF0072FF),
                                    ],
                                  ),
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(40.w),
                                  child: Image.asset(
                                    'lib/assets/login/logo@2x.png',
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              SizedBox(height: 40.h),
                              const Text(
                                '智能酒店管理系统',
                                style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              SizedBox(height: 10.h),
                              const Text(
                                'Intelligent Hotel Management System',
                                style: TextStyle(
                                  color: Color(0xFF999999),
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Form(
                          key: _frmGlobalKey,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              UsernameField(
                                controller: _txtUserNameController,
                              ),
                              SizedBox(height: 20.h),
                              PasswordField(
                                controller: _txtPwdController,
                              ),
                              SizedBox(height: 30.h),
                              RememberPasswordRow(
                                value: state.rememberPassword,
                                onChanged: (val) {
                                  cubit.toggleRememberPassword(val ?? false);
                                },
                                onForgotPassword: cubit.forgotPwd,
                              ),
                              SizedBox(height: 10.h),
                              BlocConsumer<AuthBloc, AuthState>(
                                listener: (context, authState) {
                                  if (authState is AuthFailure) {
                                    Fluttertoast.showToast(
                                      msg: authState.error,
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.CENTER,
                                      timeInSecForIosWeb: 2,
                                      backgroundColor: Colors.red,
                                      textColor: Colors.white,
                                      fontSize: 16.0,
                                    );
                                  }
                                },
                                builder: (context, authState) {
                                  return BtnLogin(
                                    isLoading: authState is AuthLoading,
                                    onPressed: () {
                                      if (_frmGlobalKey.currentState!
                                          .validate()) {
                                        cubit.login(
                                          username:
                                              _txtUserNameController.text
                                                  .trim(),
                                          password:
                                              _txtPwdController.text.trim(),
                                          rememberPassword:
                                              state.rememberPassword,
                                        );
                                      }
                                    },
                                  );
                                },
                              ),
                            ],
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}