import 'package:comwell_key_app/.generated/assets/assets.gen.dart';
import 'package:comwell_key_app/common/components/comwell_app_bar.dart';
import 'package:comwell_key_app/common/components/shimmer_loader/profile_settings_shimmer_loader.dart';
import 'package:comwell_key_app/domain/models/user.dart';
import 'package:comwell_key_app/presentation/app/bloc/profile_cubit.dart';
import 'package:country_code_picker/country_code_picker.dart';
import 'components/address_bottom_sheet.dart';
import 'components/comwell_text_field.dart';
import 'components/date_time_picker.dart';
import 'components/delete_profile_dialog_widget.dart';
import 'components/intl_phone_field.dart';
import 'components/text_field_with_trailing_icon.dart';
import 'package:comwell_key_app/domain/models/address.dart';
import 'package:comwell_key_app/utils/address_utils.dart';
import 'package:comwell_key_app/utils/l10n_utils.dart';
import 'package:concierge/presentation/theme/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:comwell_key_app/presentation/screens/profile_settings/bloc/profile_settings_cubit.dart';
import 'package:comwell_key_app/presentation/screens/profile_settings/bloc/profile_settings_state.dart';

class ProfileSettingsScreen extends StatelessWidget {
  const ProfileSettingsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final profileCubit = context.watch<ProfileCubit>();
    return BlocBuilder<ProfileSettingsCubit, ProfileSettingsState>(
      builder: (context, state) {
        if (state.isLoading) {
          return const Scaffold(
            appBar: ComwellAppBar(
              shouldShowProfileButton: false,
            ),
            backgroundColor: Colors.white,
            body: Center(child: ProfileSettingsShimmerLoader()),
          );
        }
        return _buildProfileSettingsPage(
          context,
          theme,
          state,
          profileCubit.state.user,
        );
      },
    );
  }

  Widget _buildProfileSettingsPage(
    BuildContext context,
    ThemeData theme,
    ProfileSettingsState state,
    User user,
  ) {
    final cubit = context.read<ProfileSettingsCubit>();
    final address = formatAddress(user.address);

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      appBar: const ComwellAppBar(
        shouldShowProfileButton: false,
      ),
      body: SingleChildScrollView(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: SafeArea(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 36),
                Text(
                  context.strings.profile_settings,
                  style: theme.textTheme.headlineLarge?.copyWith(color: AppColors.colorPrimaryText),
                  textAlign: TextAlign.start,
                ),
                const SizedBox(height: 36),
                ComwellTextField(
                  fieldName: context.strings.profile_settings_firstname,
                  initialValue: user.firstName,
                  readOnly: false,
                  controller: cubit.firstNameController,
                  onSubmitted: (value) {
                    cubit.updateFirstName(value);
                  },
                ),
                const SizedBox(height: 8),
                ComwellTextField(
                  fieldName: context.strings.profile_settings_lastname,
                  initialValue: user.lastName,
                  readOnly: false,
                  controller: cubit.lastNameController,
                  onSubmitted: (value) {
                    cubit.updateLastName(value);
                  },
                ),
                const SizedBox(height: 8),
                ComwellTextField(
                  fieldName: context.strings.profile_settings_email,
                  initialValue: user.email,
                  readOnly: true,
                  controller: TextEditingController(text: user.email),
                ),
                const SizedBox(height: 8),
                IntlPhoneField(
                  title: context.strings.profile_settings_phone,
                  phoneNumber: cubit.phoneNumber ?? '',
                  countryCode: cubit.countryCode ?? CountryCode.fromCountryCode('DK'),
                  controller: cubit.phoneNumberController,
                  readOnly: false,
                  onSubmitted: (value) {
                    cubit.updatePhoneNumber(value);
                  },
                ),
                const SizedBox(height: 8),
                TextFieldWithTrailingIcon(
                  title: context.strings.profile_settings_address,
                  text: address,
                  trailingIcon: "assets/icons/edit-alt.svg",
                  onTap: () async {
                    final response = await showModalBottomSheet<Address>(
                      context: context,
                      isScrollControlled: true,
                      backgroundColor: Colors.white,
                      builder: (context) => AddressBottomSheet(
                        user: user,
                        selectedCountry: cubit.selectedCountry,
                      ),
                    );

                    if (response is Address) {
                      cubit.updateAddress(response);
                    } else {
                      debugPrint("Not an address $response");
                    }
                  },
                  showTitle: true,
                ),
                const SizedBox(height: 8),
                DateTimePicker(
                  title: context.strings.profile_settings_birthday,
                  initialValue: user.birthDate ?? DateTime(1990, 1, 1),
                  onDateSelected: (date) async {
                    await cubit.updateBirthDate(date);
                  },
                ),
                const SizedBox(height: 20),
                Center(
                  child: OutlinedButton(
                    onPressed: () {
                      cubit.updateProfile();
                    },
                    style: OutlinedButton.styleFrom(
                      backgroundColor: AppColors.colorTertiary,
                      elevation: 0,
                      minimumSize: const Size(135, 40),
                      maximumSize: const Size(155, 40),
                    ),
                    child: Text(
                      context.strings.update_profile,
                      style: const TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
                Center(
                  child: OutlinedButton(
                    onPressed: () {
                      showDeleteProfileDialog(context);
                    },
                    style: OutlinedButton.styleFrom(
                      side: const BorderSide(color: AppColors.colorDivider),
                      backgroundColor: Colors.transparent,
                      shape: const RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                      ),
                      minimumSize: const Size(135, 40),
                      maximumSize: const Size(200, 40),
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Assets.icons.trashCan.svg(height: 16),
                        const SizedBox(width: 8),
                        Text(
                          context.strings.delete_profile,
                          style: theme.textTheme.labelLarge?.copyWith(
                            color: Colors.red,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> showDeleteProfileDialog(BuildContext context) {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const DeleteProfileDialogWidget();
      },
    );
  }
}