import 'package:comwell_key_app/presentation/screens/pregistration/cubit/preregistration_cubit.dart';
import 'package:comwell_key_app/presentation/screens/pregistration/components/information_card.dart';
import 'package:comwell_key_app/presentation/screens/pregistration/cubit/preregistration_state.dart';
import 'package:comwell_key_app/themes/light_theme.dart';
import 'package:comwell_key_app/utils/l10n_utils.dart';
import 'package:comwell_key_app/utils/urls.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<PreregistrationCubit, PreregistrationState>(
      builder: (context, state) {
        final cubit = context.read<PreregistrationCubit>();

        final state = cubit.state;
        final user = state.user!;
        final theme = Theme.of(context);
        final singularExtra =
            cubit.numOfExtras == 1 && cubit.state.selectedRoomUpgrade.isEmpty ||
            cubit.numOfExtras == 0 && cubit.state.selectedRoomUpgrade.isNotEmpty;
        String extrasTitleText;

        if (singularExtra) {
          extrasTitleText = context.strings.preregistration_confirmation_extras_card_title_singular;
        } else {
          extrasTitleText = context.strings.preregistration_confirmation_extras_card_title_plural(
            cubit.numOfExtras.toString(),
          );
        }

        return GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          behavior: HitTestBehavior.translucent,
          child: SafeArea(
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 12.0),
              children: [
                const SizedBox(height: 16),
                Text(
                  context.strings.preregistration_confirmation_title,
                  style: Theme.of(context).textTheme.headlineLarge,
                ),
                const SizedBox(height: 16),
                InformationCard(
                  title: context.strings.preregistration_confirmation_profile_card_title,
                  titleStyle: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                    color: colorHeadlineText,
                  ),
                  onEditClick: cubit.onEditProfileClicked,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "${state.user!.firstName} ${state.user!.lastName}",
                        style: Theme.of(context).textTheme.bodyMedium,
                      ),
                      Text(
                        user.email,
                        style: Theme.of(context).textTheme.bodyMedium,
                      ),
                      Text(
                        state.user!.phoneNumber,
                        style: Theme.of(context).textTheme.bodyMedium,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 12),
                InformationCard(
                  title: context.strings.preregistration_confirmation_address_card_title,
                  titleStyle: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                    color: colorHeadlineText,
                  ),
                  onEditClick: cubit.onEditAddressClicked,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        cubit.state.user!.address.street,
                        style: theme.textTheme.bodyMedium,
                      ),
                      Text(
                        "${state.user!.address.zipCode}, ${state.user!.address.city}${state.user!.address.country.isNotEmpty ? ', ${state.user!.address.country}' : ''}",
                        style: theme.textTheme.bodyMedium,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                // My addons section
                Text(
                  context.strings.preregistration_my_addons,
                  style: theme.textTheme.headlineSmall,
                ),
                const SizedBox(height: 8),
                Text(
                  context.strings.preregistration_my_addons_subtitle,
                  style: theme.textTheme.bodySmall?.copyWith(
                    color: colorHeadlineText,
                    fontSize: 13,
                  ),
                ),
                const SizedBox(height: 16),
                InformationCard(
                  title: extrasTitleText,
                  titleStyle: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                    color: colorHeadlineText,
                  ),
                  onEditClick: cubit.onEditExtrasClicked,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        context.strings.total_charge_value(cubit.extrasTotalPrice.toString()),
                        style: theme.textTheme.bodyMedium?.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        context.strings.preregistration_confirmation_extras_card_subtitle,
                        style: theme.textTheme.bodySmall?.copyWith(
                          color: colorHeadlineText,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 12),
                // Serving time field
                GestureDetector(
                  onTap: () async {
                    final initialTimeOfDay = state.servingTime ?? TimeOfDay.now();
                    final initialDateTime = DateTime(
                      0,
                      1,
                      1,
                      initialTimeOfDay.hour,
                      initialTimeOfDay.minute,
                    );

                    final selectedTime = await showModalBottomSheet<TimeOfDay>(
                      context: context,
                      builder: (context) {
                        DateTime tempPicked = initialDateTime;

                        return SizedBox(
                          height: 260,
                          child: Column(
                            children: [
                              Align(
                                alignment: Alignment.centerRight,
                                child: TextButton(
                                  onPressed: () {
                                    Navigator.of(context).pop(
                                      TimeOfDay(
                                        hour: tempPicked.hour,
                                        minute: tempPicked.minute,
                                      ),
                                    );
                                  },
                                  child: Text(
                                    context.strings.generic_ok,
                                    style: theme.textTheme.labelLarge?.copyWith(
                                      color: sandColor,
                                    ),
                                  ),
                                ),
                              ),
                              Expanded(
                                child: CupertinoDatePicker(
                                  mode: CupertinoDatePickerMode.time,
                                  use24hFormat: true,
                                  initialDateTime: initialDateTime,
                                  onDateTimeChanged: (DateTime newDate) {
                                    tempPicked = newDate;
                                  },
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    );

                    if (selectedTime != null) {
                      cubit.onServingTimeSelected(selectedTime);
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      border: Border.all(color: colorDivider),
                      borderRadius: const BorderRadius.all(Radius.circular(4)),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          context.strings.preregistration_serving_time_label,
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w500,
                            color: colorHeadlineText,
                          ),
                        ),
                        Text(
                          state.servingTime != null ? state.servingTime!.format(context) : '--:--',
                          style: theme.textTheme.bodyMedium,
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                // Comment field
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    border: Border.all(color: colorDivider),
                    borderRadius: const BorderRadius.all(Radius.circular(4)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        context.strings.preregistration_comment_label,
                        style: theme.textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.w500,
                          color: colorHeadlineText,
                        ),
                      ),
                      const SizedBox(height: 8),
                      TextField(
                        controller: cubit.commentTextController,
                        maxLines: 3,
                        decoration: InputDecoration(
                          hintText: context.strings.preregistration_comment_hint,
                          hintStyle: theme.textTheme.bodyMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.zero,
                        ),
                        style: theme.textTheme.bodyMedium?.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                // Accept terms checkbox
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Checkbox(
                      value: state.termsAndConditionsAccepted,
                      onChanged: (_) => cubit.onTermsAndConditionsToggled(
                        !state.termsAndConditionsAccepted,
                      ),
                      side: const BorderSide(color: colorDivider, width: 2),
                      visualDensity: VisualDensity.compact,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(4),
                      ),
                      activeColor: sandColor[80],
                    ),
                    const SizedBox(width: 4),
                    Expanded(
                      child: Wrap(
                        children: [
                          Text(
                            '${context.strings.preregistration_accept_terms_prefix} ',
                            style: theme.textTheme.bodySmall?.copyWith(
                              color: colorHeadlineText,
                              fontSize: 13,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              launchUrl(Uri.parse(ComwellUrls.clubPermission));
                            },
                            child: Text(
                              context.strings.preregistration_accept_terms_privacy_policy,
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: sandColor,
                                decoration: TextDecoration.underline,
                                decorationColor: sandColor,
                                fontSize: 13,
                              ),
                            ),
                          ),
                          Text(
                            ' ${context.strings.preregistration_accept_terms_and} ',
                            style: theme.textTheme.bodySmall?.copyWith(
                              color: colorHeadlineText,
                              fontSize: 13,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              launchUrl(Uri.parse(ComwellUrls.termsAndConditions));
                            },
                            child: Text(
                              context.strings.preregistration_accept_terms_trade_conditions,
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: sandColor,
                                decoration: TextDecoration.underline,
                                decorationColor: sandColor,
                                fontSize: 13,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 40),
              ],
            ),
          ),
        );
      },
    );
  }
}