import 'dart:math';

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

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

  @override
  ConsumerState<AdminLoginScreen> createState() => _AdminLoginScreenState();
}

class _AdminLoginScreenState extends ConsumerState<AdminLoginScreen> {
  final _formKey = GlobalKey<FormState>();

  final _businessCodeController = TextEditingController();

  final _identifierController = TextEditingController();

  final _passwordController = TextEditingController();

  final _captchaController = TextEditingController();

  late String _currentCaptcha;

  bool _obscurePassword = true;

  @override
  void initState() {
    super.initState();
    _currentCaptcha = _generateRandomCaptcha();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _businessCodeController.dispose();
    _identifierController.dispose();
    _passwordController.dispose();
    _captchaController.dispose();
    super.dispose();
  }

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

    return null;
  }

  String _generateRandomCaptcha() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    return List.generate(
      5,
      (index) => chars[Random().nextInt(chars.length)],
    ).join();
  }

  void _refreshCaptcha() {
    setState(() {
      _currentCaptcha = _generateRandomCaptcha();
    });
  }

  Future<void> _setCurrentOutlet() async {
    final currentOutletId = await SystemSetting.getCurrentOutletId();

    final currentOutletName = await SystemSetting.getCurrentOutletName();

    ref.read(currentOutletIdProvider.notifier).state = currentOutletId;

    ref.read(currentOutletNameProvider.notifier).state = currentOutletName;
  }

  Future<void> _setCurrentUser() async {
    final currentUserId = await SystemSetting.getCurrentUserId();

    final currentUserName = await SystemSetting.getCurrentUserName();

    final currentUserEmail = await SystemSetting.getCurrentUserEmail();

    final currentUserRole = await SystemSetting.getCurrentUserRole();

    final outletIdByOwner = await SystemSetting.getOutletIdByOwner();

    ref.read(currentUserIdProvider.notifier).state = currentUserId;

    ref.read(currentUserNameProvider.notifier).state = currentUserName;

    ref.read(currentUserEmailProvider.notifier).state = currentUserEmail;

    ref.read(currentUserRoleProvider.notifier).state = currentUserRole;

    ref.read(outletIdByOwnerProvider.notifier).state = outletIdByOwner;

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

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

    if (_captchaController.text.toUpperCase() != _currentCaptcha) {
      CustomSnackbar.showError(context, "Kode captcha salah!");
      _refreshCaptcha();
      return;
    }

    try {
      final businessCode = _businessCodeController.text.trim();

      final identifier = _identifierController.text.trim();

      final password = _passwordController.text.trim();

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

      if (!mounted) return;

      await _setCurrentOutlet();

      await _setCurrentUser();

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

      _refreshCaptcha();

      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 bool isTablet = 100.w >= 600;

        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: SafeArea(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 5.h),
                child: Form(
                  key: _formKey,
                  child: Column(
                    children: [
                      Image.asset(AppAsset.LOGO_UPDATE, height: 12.h),

                      SizedBox(height: 2.5.h),

                      Text(
                        "Masuk Akun Staf",
                        style: TextStyle(
                          fontSize: AppFontSize.large.sp,
                          fontWeight: FontWeight.bold,
                          color: AppColor.primaryColor,
                        ),
                      ),
                      SizedBox(height: 1.h),
                      Text(
                        "Kemajuan outlet perusahaan ada di tangan anda, berikan yang terbaik!",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                          color: Colors.grey,
                        ),
                      ),

                      SizedBox(height: 4.h),

                      CustomTextFormField(
                        label: "ID Usaha/Perusahaan",
                        hint: "xxxxxxxx",
                        controller: _businessCodeController,
                        prefixIcon: Icons.business_outlined,
                        validator: (value) => _validation(
                          value: value,
                          message: "ID Perusahaan belum diisi",
                        ),
                        readOnly: isLoading,
                      ),

                      SizedBox(height: 2.5.h),

                      CustomTextFormField(
                        label: "Email atau No. WhatsApp",
                        hint: "contoh@email.com / 0812...",
                        controller: _identifierController,
                        prefixIcon: Icons.person_outline,
                        validator: (value) => _validation(
                          value: value,
                          message: "Kolom ini belum diisi",
                        ),
                        readOnly: isLoading,
                      ),

                      SizedBox(height: 2.5.h),

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

                      SizedBox(height: 2.5.h),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Expanded(
                            flex: 2,
                            child: CustomTextFormField(
                              label: "Kode Captcha",
                              hint: "Input kode",
                              controller: _captchaController,
                              validator: (value) => _validation(
                                value: value,
                                message: "captcha belum diisi",
                              ),
                              readOnly: isLoading,
                            ),
                          ),
                          SizedBox(width: 4.w),
                          InkWell(
                            onTap: _refreshCaptcha,
                            borderRadius: BorderRadius.circular(2.w),
                            child: Container(
                              height: 7.h,
                              width: 30.w,
                              decoration: BoxDecoration(
                                color: Colors.grey[200],
                                borderRadius: BorderRadius.circular(2.w),
                                border: Border.all(color: Colors.grey[300]!),
                              ),
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  CustomPaint(
                                    size: Size(32.w, 6.5.h),
                                    painter: CaptchaNoisePainter(),
                                  ),
                                  Text(
                                    _currentCaptcha,
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontStyle: FontStyle.italic,
                                      letterSpacing: 4,
                                      fontSize: isTablet
                                          ? AppFontSize.medium.sp
                                          : AppFontSize.small.sp,
                                      color: Colors.black87,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),

                      Align(
                        alignment: Alignment.centerRight,
                        child: TextButton(
                          onPressed: () =>
                              context.pushNamed(AppRoute.forgotPasswordScreen),
                          child: Text(
                            "Lupa Password?",
                            style: TextStyle(
                              color: AppColor.primaryColor,
                              fontWeight: FontWeight.bold,
                              fontSize: isTablet
                                  ? (AppFontSize.medium - 1.25).sp
                                  : (AppFontSize.small - 1.25).sp,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: 2.5.h),

                      ElevatedButton(
                        onPressed: authControllerState.isLoading
                            ? null
                            : _handleLogin,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          minimumSize: Size(double.infinity, 7.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(3.w),
                          ),
                          elevation: 2,
                        ),
                        child: Text(
                          "Masuk Sekarang",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),

                      SizedBox(height: 4.h),

                      _buildOwnerLink(isTablet),

                      SizedBox(height: 2.5.h),

                      Text(
                        "Powered By P.T. Niaga Nusantara",
                        style: TextStyle(
                          color: Colors.grey.shade600,
                          fontWeight: FontWeight.w500,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                      ),
                      SizedBox(height: 0.75.h),
                      Text(
                        "Versi 1.0.0",
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildOwnerLink(bool isTablet) {
    return Material(
      color: Colors.blue[50],
      borderRadius: BorderRadius.circular(3.w),
      child: InkWell(
        onTap: () => context.pop(),
        borderRadius: BorderRadius.circular(3.w),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.blue[100]!),
            borderRadius: BorderRadius.circular(3.w),
          ),
          child: Row(
            children: [
              Icon(Icons.info_outline, color: Colors.blue[700], size: 5.w),
              SizedBox(width: 3.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "Apakah anda pemilik usaha?",
                      style: TextStyle(
                        color: Colors.blue[900],
                        fontSize: isTablet
                            ? (AppFontSize.medium - 1.25).sp
                            : (AppFontSize.small - 1.25).sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 0.5.h),
                    Text(
                      "Masuk sebagai pemilik di sini",
                      style: TextStyle(
                        color: AppColor.primaryColor,
                        fontSize: isTablet
                            ? (AppFontSize.medium - 0.5).sp
                            : (AppFontSize.small - 0.5).sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
              Icon(Icons.chevron_right, color: Colors.blue[300], size: 5.w),
            ],
          ),
        ),
      ),
    );
  }
}
