import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.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/providers/app_provider.dart';
import 'package:niogu_app/core/utils/date_input_formatter.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/profile/domain/entities/profile.dart';
import 'package:niogu_app/features/profile/presentation/providers/profile_provider.dart';
import 'package:sizer/sizer.dart';

class ProfileInfoScreen extends ConsumerStatefulWidget {
  final ProfileInfo profileInfo;
  const ProfileInfoScreen({super.key, required this.profileInfo});

  @override
  ConsumerState<ProfileInfoScreen> createState() => _ProfileInfoScreenState();
}

class _ProfileInfoScreenState extends ConsumerState<ProfileInfoScreen> {
  /**  
  String? _validateUsername(String? value) {
    if (value == null || value.isEmpty) return "Username tidak boleh kosong";
    if (value.length < 5) return "Username minimal 5 karakter";

    final RegExp usernameRegExp = RegExp(
      r'^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$',
    );

    if (!usernameRegExp.hasMatch(value)) {
      return "Username hanya boleh huruf kecil, angka, _ dan .";
    }
    return null;
  }
  */

  final _formKey = GlobalKey<FormState>();

  late final String _email;

  late final String _phoneNumber;

  final TextEditingController _nameController = TextEditingController();

  final TextEditingController _placeOfBirthController = TextEditingController();

  final TextEditingController _dateOfBirthController = TextEditingController();

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

    final profileInfo = widget.profileInfo;

    _nameController.text = profileInfo.name;

    _email = profileInfo.email;

    _phoneNumber = profileInfo.phoneNumber;

    if (profileInfo.placeOfBirth != null &&
        profileInfo.placeOfBirth!.isNotEmpty) {
      _placeOfBirthController.text = profileInfo.placeOfBirth!;
    }

    if (profileInfo.dateOfBirth != null &&
        profileInfo.dateOfBirth!.isNotEmpty) {
      _dateOfBirthController.text = profileInfo.dateOfBirth!;
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _nameController.dispose();
    _placeOfBirthController.dispose();
    _dateOfBirthController.dispose();
    super.dispose();
  }

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

    final profile = UpsertProfile(
      name: _nameController.text.trim(),
      placeOfBirth: _placeOfBirthController.text.trim(),
      dateOfBirth: _dateOfBirthController.text.trim(),
    );

    try {
      await ref.read(profileControllerProvider.notifier).updateProfile(profile);

      if (!mounted) return;

      final currentUserName = await SystemSetting.getCurrentUserName();

      if (currentUserName != profile.name) {
        await SystemSetting.setUser(userName: profile.name);
        ref.read(currentUserNameProvider.notifier).state = profile.name;
      }

      CustomSnackbar.showSuccess(context, "Informasi profil berhasil di ubah");
      context.pop();
    } 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 profileControllerState = ref.watch(profileControllerProvider);
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Informasi Profil",
              onTap: () => Navigator.pop(context),
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    CircleAvatar(
                      radius: 12.w,
                      backgroundColor: Colors.grey[200],
                      child: Icon(
                        Icons.person,
                        size: 12.w,
                        color: Colors.grey[400],
                      ),
                    ),

                    SizedBox(height: 4.h),

                    /**
                      CustomTextFormField(
                        label: "Username",
                        hint: "Contoh: ali_akbar",
                        controller: TextEditingController(),
                        prefixIcon: Icons.alternate_email,
                        validator: _validateUsername,
                        readOnly: true,
                      ),
                    
                    SizedBox(height: 2.h),
                    */
                    CustomTextFormField(
                      label: "Nama",
                      hint: "Masukkan nama lengkap Anda",
                      controller: _nameController,
                      prefixIcon: Icons.person_outline,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return "Nama belum diisi";
                        }

                        return null;
                      },
                    ),
                    SizedBox(height: 2.h),
                    CustomTextFormField(
                      label: "Email",
                      hint: "nama@email.com",
                      controller: TextEditingController(text: _email),
                      prefixIcon: Icons.email_outlined,
                      keyboardType: TextInputType.emailAddress,
                      readOnly: true,
                    ),
                    SizedBox(height: 2.h),
                    CustomTextFormField(
                      label: "No HP / WhatsApp",
                      hint: "0812xxxx",
                      controller: TextEditingController(text: _phoneNumber),
                      prefixIcon: Icons.phone_android,
                      keyboardType: TextInputType.phone,
                      readOnly: true,
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      children: [
                        Expanded(
                          child: CustomTextFormField(
                            label: "Tempat Lahir",
                            hint: "Jakarta",
                            controller: _placeOfBirthController,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Expanded(
                          child: CustomTextFormField(
                            label: "Tanggal Lahir",
                            hint: "31/12/1999",
                            controller: _dateOfBirthController,
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(
                                RegExp(r'[0-9/]'),
                              ),
                              DateInputFormatter(),
                            ],
                            prefixIcon: Icons.calendar_today_outlined,
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 5.h),
                    ElevatedButton(
                      onPressed: profileControllerState.isLoading
                          ? null
                          : _updateProfile,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        minimumSize: Size(double.infinity, 7.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.w),
                        ),
                        disabledBackgroundColor: Colors.grey.shade300,
                      ),
                      child: Text(
                        "Simpan Perubahan",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
