import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_asset.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/providers/app_provider.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/system/system_setting.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_text_form_field.dart';
import 'package:niogu_ecommerce_v1/features/auth/presentation/providers/auth_provider.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends ConsumerState<LoginScreen> {
  final _formKey = GlobalKey<FormState>();

  final _identifierController = TextEditingController();

  final _passwordController = TextEditingController();

  bool _obsecurePassword = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

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

  Future<void> _setCustomerInfo() async {
    final customerId = await SystemSetting.getCurrentCustomerId();

    final customerName = await SystemSetting.getCurrentCustomerName();

    final customerEmail = await SystemSetting.getCurrentCustomerEmail();

    final customerPhone = await SystemSetting.getCurrentCustomerPhone();

    ref.read(currentCustomerIdProvider.notifier).state = customerId;

    ref.read(currentCustomerNameProvider.notifier).state = customerName;

    ref.read(currentCustomerEmailProvider.notifier).state = customerEmail;

    ref.read(currentCustomerPhoneProvider.notifier).state = customerPhone;

    ref.read(currentStatusLoginProvider.notifier).state = true;
  }

  String? _validation({String? value, required String message}) {
    if (value == null || value.isEmpty) {
      return message;
    }

    return null;
  }

  Future<void> _login() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      final identifier = _identifierController.text.trim();

      final password = _passwordController.text.trim();

      await ref
          .read(authControllerProvider.notifier)
          .login(identifier: identifier, password: password);

      if (!mounted) return;

      await _setCustomerInfo();
      CustomSnackbar.showSuccess(context, "Berhasil login");
      context.goNamed(AppRoute.homeScreen);
    } on ServerException catch (e) {
      CustomSnackbar.showError(context, e.message);
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final authControllerState = ref.watch(authControllerProvider);

        final isLoading = authControllerState.isLoading;

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 7.w),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 8.h),

                    Center(
                      child: Container(
                        height: 15.h,
                        width: 15.h,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(AppAsset.LOGO),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 5.h),

                    Text(
                      "Selamat Datang",
                      style: TextStyle(
                        fontSize: AppFontSize.medium.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 1.h),
                    Text(
                      "Silakan masuk ke akun Anda untuk mulai belanja.",
                      style: TextStyle(
                        fontSize: AppFontSize.small.sp,
                        color: Colors.grey.shade600,
                      ),
                    ),

                    SizedBox(height: 5.h),

                    CustomTextFormField(
                      label: "Email atau No. Whatsapp",
                      hint: "@gmail.com",
                      controller: _identifierController,
                      prefixIcon: Icons.person_outline_rounded,
                      validator: (value) => _validation(
                        value: value,
                        message: "Kolom ini belum diisi",
                      ),
                      readOnly: isLoading,
                    ),
                    SizedBox(height: 3.h),

                    CustomTextFormField(
                      label: "Password",
                      hint: "••••••••",
                      controller: _passwordController,
                      isObscure: _obsecurePassword,
                      prefixIcon: Icons.lock_outline_rounded,
                      suffixIcon: _obsecurePassword
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                      suffixPressed: () {
                        setState(() {
                          _obsecurePassword = !_obsecurePassword;
                        });
                      },
                      validator: (value) => _validation(
                        value: value,
                        message: "Password belum diisi",
                      ),
                      readOnly: isLoading,
                    ),

                    SizedBox(height: 2.h),

                    Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        "Lupa Kata Sandi?",
                        style: TextStyle(
                          color: AppColor.primaryColor,
                          fontWeight: FontWeight.bold,
                          fontSize: (AppFontSize.small - 1).sp,
                        ),
                      ),
                    ),

                    SizedBox(height: 5.h),

                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: isLoading ? null : _login,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          padding: EdgeInsets.symmetric(vertical: 2.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                          elevation: 0,
                          disabledBackgroundColor: Colors.grey.shade300,
                        ),
                        child: Text(
                          "Masuk",
                          style: TextStyle(
                            fontSize: AppFontSize.medium.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 4.h),

                    Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Belum punya akun? ",
                            style: TextStyle(
                              fontSize: (AppFontSize.small - 1.25).sp,
                            ),
                          ),
                          SizedBox(width: 0.5.w),
                          TextButton(
                            onPressed: () {
                              context.pushNamed(AppRoute.registerScreen);
                            },
                            style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                              minimumSize: Size.zero,
                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              overlayColor: Colors.transparent,
                            ),
                            child: Text(
                              "Daftar Sekarang",
                              style: TextStyle(
                                color: AppColor.primaryColor,
                                fontWeight: FontWeight.bold,
                                fontSize: (AppFontSize.small - 1.25).sp,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
