import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/common/str_extensions.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_date_selector.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_dropdown.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_phone_input.dart';
import 'package:krow/features/profile/wages_forms/domain/bloc/wages_form_bloc.dart';
import 'package:krow/features/profile/wages_forms/domain/entities/i_nine_entity.dart';
import 'package:krow/features/profile/wages_forms/presentation/mixins/form_updater_mixin.dart';
import 'package:krow/features/profile/wages_forms/presentation/widgets/form_sign_holder_widget.dart';

@RoutePage()
class INineFormScreen extends StatefulWidget {
  const INineFormScreen({super.key});

  @override
  State<INineFormScreen> createState() => _INineFormScreenState();
}

class _INineFormScreenState extends State<INineFormScreen>
    with FormUpdaterMixin<INineFormScreen, INineEntity> {
  @override
  void initState() {
    super.initState();

    final activeForm = context.read<WagesFormBloc>().state.activeForm;
    form = activeForm is INineEntity ? activeForm : const INineEntity.empty();
  }

  @override
  Widget build(BuildContext context) {
    final currentData = DateTime.now();

    return Scaffold(
      appBar: KwAppBar(
        titleText: 'I-9',
        showNotification: true,
      ),
      body: BlocConsumer<WagesFormBloc, WagesFormState>(
        listenWhen: (previous, current) =>
            current.status == StateStatus.success,
        buildWhen: (previous, current) => current.status == StateStatus.error,
        listener: (context, state) {
          context.pushRoute(const SignedFormRoute());
          updateCurrentForm(form.copyWith(isSigned: true));
        },
        builder: (context, state) {
          final formErrors = state.formErrors;

          return ListView(
            primary: false,
            padding: const EdgeInsets.all(16),
            children: [
              const Text(
                'Fill the form below:',
                style: AppTextStyles.bodySmallRegBlackGrey,
              ),
              const Gap(24),
              KwTextInput(
                initialValue: form.lastName,
                onChanged: (lastName) {
                  updateCurrentForm(form.copyWith(lastName: lastName));
                },
                title: 'Last Name (Family Name)',
                hintText: 'Enter your Last name',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.name,
                textCapitalization: TextCapitalization.sentences,
                showError: formErrors.containsKey(WagesFormFields.lastName),
                helperText: formErrors[WagesFormFields.lastName],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.firstName,
                onChanged: (firstName) {
                  updateCurrentForm(form.copyWith(firstName: firstName));
                },
                title: 'First Name (Given Name)',
                hintText: 'Enter your First name',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.name,
                textCapitalization: TextCapitalization.sentences,
                showError: formErrors.containsKey(WagesFormFields.firstName),
                helperText: formErrors[WagesFormFields.firstName],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.middleName,
                onChanged: (middleName) {
                  updateCurrentForm(form.copyWith(middleName: middleName));
                },
                title: 'Middle Initial (if any)',
                hintText: 'Enter your Middle name',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.name,
                textCapitalization: TextCapitalization.sentences,
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.address,
                onChanged: (address) {
                  updateCurrentForm(form.copyWith(address: address));
                },
                title: 'Address',
                hintText: 'Enter your Address name',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.name,
                textCapitalization: TextCapitalization.sentences,
                showError: formErrors.containsKey(WagesFormFields.address),
                helperText: formErrors[WagesFormFields.address],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.aptNumber?.toString(),
                onChanged: (apt) {
                  updateCurrentForm(
                    form.copyWith(aptNumber: int.tryParse(apt)),
                  );
                },
                title: 'Apt. Number (if any)',
                hintText: 'Enter your Apt. Number',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.number,
                showError: false,
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.city,
                onChanged: (city) {
                  updateCurrentForm(form.copyWith(city: city));
                },
                title: 'City or Town',
                hintText: 'Enter your City',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.name,
                textCapitalization: TextCapitalization.sentences,
                showError: formErrors.containsKey(WagesFormFields.city),
                helperText: formErrors[WagesFormFields.city],
              ),
              const Gap(8),
              KwDropdown<String>(
                title: 'State',
                horizontalPadding: 16,
                borderColor: AppColors.grayStroke,
                hintText: 'Select state',
                selectedItem: form.state.toDropDownItem(),
                items: [
                  for (final state in usStates)
                    KwDropDownItem(data: state, title: state),
                ],
                onSelected: (state) {
                  updateCurrentForm(form.copyWith(state: state));
                },
                showError: formErrors.containsKey(WagesFormFields.state),
                helperText: formErrors[WagesFormFields.state],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.zipCode,
                onChanged: (zipCode) {
                  updateCurrentForm(form.copyWith(zipCode: zipCode));
                },
                title: 'ZIP Code',
                hintText: 'Enter your City\'s ZIP code',
                borderColor: AppColors.grayStroke,
                keyboardType: TextInputType.number,
                textInputAction: TextInputAction.next,
                showError: formErrors.containsKey(WagesFormFields.zipCode),
                helperText: formErrors[WagesFormFields.zipCode],
              ),
              const Gap(8),
              KwDateSelector(
                title: 'Date of Birth',
                hintText: 'mm/dd/yyyy',
                initialValue: form.dateOfBirth,
                firstDate: currentData.subtract(const Duration(days: 36500)),
                lastDate: currentData.subtract(const Duration(days: 3650)),
                initialDate: currentData.subtract(const Duration(days: 6570)),
                onSelect: (date) {
                  updateCurrentForm(form.copyWith(dateOfBirth: date));
                },
                showError: formErrors.containsKey(WagesFormFields.birthdate),
                helperText: formErrors[WagesFormFields.birthdate],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.socialNumber,
                onChanged: (socialNumber) {
                  updateCurrentForm(form.copyWith(socialNumber: socialNumber));
                },
                title: 'U.S. Social Number',
                hintText: 'Enter your U.S. Social Number',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                showError: formErrors.containsKey(WagesFormFields.socialNumber),
                helperText: formErrors[WagesFormFields.socialNumber],
              ),
              const Gap(8),
              KwTextInput(
                initialValue: form.email,
                onChanged: (email) {
                  updateCurrentForm(form.copyWith(email: email));
                },
                title: 'Employee’s Email Address',
                hintText: 'Enter your Email',
                borderColor: AppColors.grayStroke,
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.emailAddress,
                showError: formErrors.containsKey(WagesFormFields.email),
                helperText: formErrors[WagesFormFields.email],
              ),
              const Gap(8),
              KwPhoneInput(
                title: 'Phone Number',
                initialValue: form.phoneNumber,
                onChanged: (phone) {
                  updateCurrentForm(form.copyWith(phoneNumber: phone));
                },
                borderColor: AppColors.grayStroke,
                showError: formErrors.containsKey(WagesFormFields.phone),
                helperText: formErrors[WagesFormFields.phone],
              ),
              const Gap(24),
              const FormSignHolderWidget(signingPageTitle: 'I-9'),
              const Gap(24),
              KwDateSelector(
                readOnly: true,
                title: 'Today’s Date',
                hintText: 'mm/dd/yyyy',
                initialValue: currentData,
                onSelect: (date) {},
              ),
              const Gap(24),
              KwButton.outlinedPrimary(
                label: 'Document Preview',
                leftIcon: Assets.images.icons.eye,
                onPressed: () {
                  context.pushRoute(const FormPreviewRoute());
                },
              ),
            ],
          );
        },
      ),
      bottomNavigationBar: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: KwButton.primary(label: 'Submit', onPressed: handleSubmit),
        ),
      ),
    );
  }
}
