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/features/profile/wages_forms/domain/bloc/wages_form_bloc.dart';
import 'package:krow/features/profile/wages_forms/domain/entities/w_four_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 WFourFormScreen extends StatefulWidget {
  const WFourFormScreen({super.key});

  @override
  State<WFourFormScreen> createState() => _WFourFormScreenState();
}

class _WFourFormScreenState extends State<WFourFormScreen>
    with FormUpdaterMixin<WFourFormScreen, WFourEntity> {
  @override
  void initState() {
    super.initState();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        titleText: 'W-4',
        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.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),
              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(24),
              const FormSignHolderWidget(signingPageTitle: 'W-4'),
              const Gap(24),
              KwDateSelector(
                readOnly: true,
                title: 'Today’s Date',
                hintText: 'mm/dd/yyyy',
                initialValue: DateTime.now(),
                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),
        ),
      ),
    );
  }
}
