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/data/models/auth_model.dart';
import 'package:niogu_ecommerce_v1/features/auth/presentation/providers/auth_provider.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends ConsumerState<RegisterScreen> {
  final _formKey = GlobalKey<FormState>();

  final _nameController = TextEditingController();

  final _emailController = TextEditingController();

  final _phoneController = TextEditingController();

  final _passwordController = TextEditingController();

  final _confirmPasswordController = TextEditingController();

  bool _obsecurePassword = true;

  bool _obsecureConfirmPassword = true;

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

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.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,
    String? message,
    bool isEmail = false,
    bool isPassword = false,
    bool isPasswordConfirm = false,
  }) {
    if (value == null || value.isEmpty) {
      return message;
    }

    final _emailRegex = RegExp(
      r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
    );

    if (isEmail && !_emailRegex.hasMatch(value)) {
      return "Email tidak valid";
    }

    if (isPassword) {
      if (value.length < 8) {
        return "Password minimal harus 8 karakter";
      }

      final passwordRegExp = RegExp(
        r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$',
      );

      if (!passwordRegExp.hasMatch(value)) {
        return "Gunakan huruf besar, kecil, angka, dan simbol";
      }
    }

    if (isPasswordConfirm && value != _passwordController.text.trim()) {
      return "Konfirmasi password tidak sesuai";
    }

    return null;
  }

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

    try {
      await ref
          .read(authControllerProvider.notifier)
          .register(
            RegisterRequest(
              name: _nameController.text.trim(),
              phoneNumber: _phoneController.text.trim(),
              password: _passwordController.text.trim(),
            ),
          );

      await ref
          .read(authControllerProvider.notifier)
          .login(
            identifier: _phoneController.text.trim(),
            password: _passwordController.text.trim(),
          );

      if (!mounted) return;

      await _setCustomerInfo();

      CustomSnackbar.showSuccess(context, "Berhasil login");
      context.goNamed(AppRoute.homeScreen);
    } on ServerException catch (e) {
      if (!mounted) ;

      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: Image.asset(
                        AppAsset.LOGO,
                        height: 15.h,
                        width: 15.h,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) =>
                            CircleAvatar(
                              radius: 10.w,
                              backgroundColor: AppColor.primaryColor
                                  .withOpacity(0.1),
                              child: Icon(
                                Icons.person_add_outlined,
                                size: 10.w,
                                color: AppColor.primaryColor,
                              ),
                            ),
                      ),
                    ),

                    SizedBox(height: 3.h),
                    Text(
                      "Buat Akun Baru",
                      style: TextStyle(
                        fontSize: AppFontSize.medium.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 1.h),
                    Text(
                      "Lengkapi data di bawah ini untuk mendaftar.",
                      style: TextStyle(
                        fontSize: AppFontSize.small.sp,
                        color: Colors.grey.shade600,
                      ),
                    ),

                    SizedBox(height: 4.h),

                    CustomTextFormField(
                      label: "Nama Lengkap",
                      hint: "Masukkan nama lengkap",
                      controller: _nameController,
                      prefixIcon: Icons.person_outline,
                      validator: (value) => _validation(
                        value: value,
                        message: "Nama lengkap belum diisi",
                      ),
                      readOnly: isLoading,
                    ),

                    SizedBox(height: 2.5.h),

                    CustomTextFormField(
                      label: "Email",
                      hint: "@gmail.com",
                      controller: _emailController,
                      keyboardType: TextInputType.emailAddress,
                      prefixIcon: Icons.email_outlined,
                      validator: (value) =>
                          _validation(value: value, isEmail: true),
                      readOnly: isLoading,
                    ),

                    SizedBox(height: 2.5.h),

                    CustomTextFormField(
                      label: "No. Whatsapp",
                      hint: "08123456xxx",
                      controller: _phoneController,
                      keyboardType: TextInputType.phone,
                      prefixIcon: Icons.person_outline_rounded,
                      validator: (value) => _validation(
                        value: value,
                        message: "No. Whatsapp belum diisi",
                      ),
                      readOnly: isLoading,
                    ),

                    SizedBox(height: 2.5.h),

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

                    SizedBox(height: 2.5.h),

                    CustomTextFormField(
                      label: "Konfirmasi Password",
                      hint: "••••••••",
                      controller: _confirmPasswordController,
                      isObscure: _obsecureConfirmPassword,
                      prefixIcon: Icons.lock_outline,
                      suffixIcon: _obsecureConfirmPassword
                          ? Icons.visibility
                          : Icons.visibility_off,
                      suffixPressed: () {
                        setState(() {
                          _obsecureConfirmPassword = !_obsecureConfirmPassword;
                        });
                      },
                      validator: (value) => _validation(
                        value: value,
                        message: "Konfirmasi password belum diisi",
                        isPasswordConfirm: true,
                      ),
                      readOnly: isLoading,
                    ),

                    SizedBox(height: 5.h),

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

                    SizedBox(height: 3.h),
                    Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "Sudah punya akun? ",
                            style: TextStyle(
                              fontSize: (AppFontSize.small - 1.25).sp,
                            ),
                          ),
                          SizedBox(width: 0.5.w),
                          TextButton(
                            onPressed: () => context.pop(),
                            style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                              minimumSize: Size.zero,
                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              overlayColor: Colors.transparent,
                            ),
                            child: Text(
                              "Masuk di sini",
                              style: TextStyle(
                                color: AppColor.primaryColor,
                                fontWeight: FontWeight.bold,
                                fontSize: (AppFontSize.small - 1.25).sp,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 5.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
