import 'dart:io';
import 'package:english_learning/core/services/constants.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/core/widgets/custom_snackbar.dart';
import 'package:english_learning/core/widgets/form_field/custom_field_widget.dart';
import 'package:english_learning/core/widgets/global_button.dart';
import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/settings/modules/edit_profile/widgets/save_changes_dialog.dart';
import 'package:english_learning/features/settings/widgets/user_avatar.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class EditProfileScreen extends StatefulWidget {
  const EditProfileScreen({super.key});

  @override
  State<EditProfileScreen> createState() => _EditProfileScreenState();
}

class _EditProfileScreenState extends State<EditProfileScreen> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _nisnController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final userProvider = Provider.of<UserProvider>(context, listen: false);
      _nameController.text = userProvider.userData?['NAME_USERS'] ?? '';
      _emailController.text = userProvider.userData?['EMAIL'] ?? '';
      _nisnController.text = userProvider.userData?['NISN']?.toString() ?? '';
    });
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _nisnController.dispose();
    super.dispose();
  }

  Future<void> _updateUserProfile(BuildContext context) async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);

    // Validasi input
    if (_nameController.text.isEmpty || _emailController.text.isEmpty) {
      CustomSnackBar.show(
        context,
        message: 'Please fill all required fields',
        isError: true,
      );
      return;
    }

    final updatedData = {
      'NAME_USERS': _nameController.text,
      'EMAIL': _emailController.text,
      'NISN': _nisnController.text,
    };

    try {
      userProvider.setLoading(true);
      await userProvider.updateUserProfile(updatedData);
      userProvider.setLoading(false);

      showDialog(
        context: context,
        builder: (BuildContext context) {
          return SaveChangesDialog(
            onSubmit: () {
              Navigator.pop(context); // Close the dialog
              Navigator.pop(context); // Go back to the previous screen
            },
          );
        },
      );
    } catch (e) {
      userProvider.setLoading(false);

      CustomSnackBar.show(
        context,
        message: 'Failed to update profile. Please try again.',
        isError: true,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        iconTheme: const IconThemeData(color: AppColors.whiteColor),
        centerTitle: true,
        title: Text(
          'Edit Profile',
          style: AppTextStyles.whiteTextStyle.copyWith(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: AppColors.gradientTheme,
          ),
        ),
      ),
      body: Consumer<UserProvider>(builder: (context, userProvider, child) {
        return SingleChildScrollView(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              alignment: Alignment.bottomCenter,
              children: [
                Padding(
                  padding: const EdgeInsets.only(bottom: 50.0),
                  child: Container(
                    width: double.infinity,
                    height: 100,
                    decoration: BoxDecoration(
                      gradient: AppColors.gradientTheme,
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(24),
                        bottomRight: Radius.circular(24),
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  child: UserAvatar(
                    radius: 60,
                    pictureUrl: userProvider.userData?['PICTURE'],
                    baseUrl: '${baseUrl}api/uploads/avatar/',
                    onImageSelected: (File image) {
                      userProvider.setSelectedImage(image);
                    },
                    selectedImage: userProvider.selectedImage,
                    showCameraIcon: true,
                    isLoading: userProvider.isLoading,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 39),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Column(
                children: [
                  CustomFieldWidget(
                    fieldName: 'nisn',
                    controller: _nisnController,
                    isEnabled: false,
                    isRequired: false,
                    textInputAction: TextInputAction.next,
                    labelText: 'NISN',
                  ),
                  const SizedBox(height: 20),
                  CustomFieldWidget(
                    fieldName: 'class',
                    isEnabled: false,
                    isRequired: false,
                    textInputAction: TextInputAction.next,
                    labelText: 'Class',
                    hintText: userProvider.userData?['NAME_CLASS']?.toString(),
                    keyboardType: TextInputType.number,
                  ),
                  const SizedBox(height: 20),
                  CustomFieldWidget(
                    fieldName: 'fullname',
                    controller: _nameController,
                    isRequired: true,
                    textInputAction: TextInputAction.next,
                    labelText: 'Full Name',
                    keyboardType: TextInputType.text,
                  ),
                  const SizedBox(height: 20),
                  CustomFieldWidget(
                    fieldName: 'email',
                    controller: _emailController,
                    isRequired: true,
                    textInputAction: TextInputAction.next,
                    labelText: 'Email Address',
                    keyboardType: TextInputType.emailAddress,
                  ),
                  const SizedBox(height: 24),
                  GlobalButton(
                    text: 'Save Changes',
                    isLoading: userProvider.isLoading,
                    onPressed: userProvider.isLoading
                        ? null
                        : () => _updateUserProfile(context),
                  ),
                ],
              ),
            ),
          ],
        ));
      }),
    );
  }
}
