import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../application/auth/auth_bloc.dart';
import '../../../../../application/user/user_edit_form/user_edit_form_bloc.dart';
import '../../../../../common/extension/extension.dart';
import '../../../../../common/theme/theme.dart';
import '../../../../../domain/user/user.dart';
import '../../../../../injection.dart';
import '../../../../components/appbar/appbar.dart';
import '../../../../components/button/button.dart';
import '../../../../components/spacer/spacer.dart';
import '../../../../components/toast/flushbar.dart';
import 'widgets/name_field.dart';

@RoutePage()
class ProfileEditPage extends StatefulWidget implements AutoRouteWrapper {
  final User user;
  const ProfileEditPage({super.key, required this.user});

  @override
  State<ProfileEditPage> createState() => _ProfileEditPageState();

  @override
  Widget wrappedRoute(BuildContext context) =>
      BlocProvider(create: (_) => getIt<UserEditFormBloc>(), child: this);
}

class _ProfileEditPageState extends State<ProfileEditPage> {
  TextEditingController nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    nameController = TextEditingController(text: widget.user.name);
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<UserEditFormBloc, UserEditFormState>(
      listenWhen: (p, c) => p.failureOrUserOption != c.failureOrUserOption,
      listener: (context, state) {
        state.failureOrUserOption.fold(
          () => null,
          (either) => either.fold(
            (f) => AppFlushbar.showUserFailureToast(context, f),
            (user) {
              if (context.mounted) {
                context.read<AuthBloc>().add(AuthEvent.fetchCurrentUser());
                context.router.back();
              }
            },
          ),
        );
      },
      child: Scaffold(
        backgroundColor: AppColor.background,
        body: CustomScrollView(
          slivers: [
            // SliverAppBar with gradient
            SliverAppBar(
              expandedHeight: 120,
              floating: false,
              pinned: true,
              elevation: 0,
              backgroundColor: AppColor.primary,
              flexibleSpace: CustomAppBar(title: context.lang.edit_profile),
            ),
            SliverToBoxAdapter(
              child: BlocBuilder<UserEditFormBloc, UserEditFormState>(
                builder: (context, state) {
                  return Container(
                    margin: EdgeInsets.all(AppValue.margin),
                    padding: EdgeInsets.all(AppValue.padding),
                    decoration: BoxDecoration(
                      color: AppColor.white,
                      borderRadius: BorderRadius.circular(AppValue.radius),
                    ),
                    child: Form(
                      autovalidateMode: state.showErrorMessages
                          ? AutovalidateMode.always
                          : AutovalidateMode.disabled,
                      child: Column(
                        children: [
                          ProfileEditNameField(controller: nameController),
                          SpaceHeight(24),
                          AppElevatedButton(
                            text: context.lang.save,
                            isLoading: state.isSubmitting,
                            onPressed: () {
                              context.read<UserEditFormBloc>().add(
                                UserEditFormEvent.submitted(),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
