import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_core/core.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../blocs/one_time_order_bloc.dart';
import '../../blocs/one_time_order_event.dart';
import '../../blocs/one_time_order_state.dart';
import 'one_time_order_date_picker.dart';
import 'one_time_order_event_name_input.dart';
import 'one_time_order_header.dart';
import 'one_time_order_position_card.dart';
import 'one_time_order_section_header.dart';
import 'one_time_order_success_view.dart';

/// The main content of the One-Time Order page.
class OneTimeOrderView extends StatelessWidget {
  /// Creates a [OneTimeOrderView].
  const OneTimeOrderView({super.key});

  @override
  Widget build(BuildContext context) {
    final TranslationsClientCreateOrderOneTimeEn labels =
        t.client_create_order.one_time;

    return BlocConsumer<OneTimeOrderBloc, OneTimeOrderState>(
      listener: (BuildContext context, OneTimeOrderState state) {
        if (state.status == OneTimeOrderStatus.failure &&
            state.errorMessage != null) {
          UiSnackbar.show(
            context,
            message: translateErrorKey(state.errorMessage!),
            type: UiSnackbarType.error,
            margin: const EdgeInsets.only(bottom: 140, left: 16, right: 16),
          );
        }
      },
      builder: (BuildContext context, OneTimeOrderState state) {
        if (state.status == OneTimeOrderStatus.success) {
          return OneTimeOrderSuccessView(
            title: labels.success_title,
            message: labels.success_message,
            buttonLabel: labels.back_to_orders,
            onDone: () => Modular.to.pushNamedAndRemoveUntil(
              ClientPaths.orders,
              (_) => false,
              arguments: <String, dynamic>{
                'initialDate': state.date.toIso8601String(),
              },
            ),
          );
        }

        if (state.vendors.isEmpty &&
            state.status != OneTimeOrderStatus.loading) {
          return Scaffold(
            body: Column(
              children: <Widget>[
                OneTimeOrderHeader(
                  title: labels.title,
                  subtitle: labels.subtitle,
                  onBack: () => Modular.to.navigate(ClientPaths.createOrder),
                ),
                Expanded(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        const Icon(
                          UiIcons.search,
                          size: 64,
                          color: UiColors.iconInactive,
                        ),
                        const SizedBox(height: UiConstants.space4),
                        Text(
                          'No Vendors Available',
                          style: UiTypography.headline3m.textPrimary,
                        ),
                        const SizedBox(height: UiConstants.space2),
                        Text(
                          'There are no staffing vendors associated with your account.',
                          style: UiTypography.body2r.textSecondary,
                          textAlign: TextAlign.center,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        }

        return Scaffold(
          body: Column(
            children: <Widget>[
              OneTimeOrderHeader(
                title: labels.title,
                subtitle: labels.subtitle,
                onBack: () => Modular.to.navigate(ClientPaths.createOrder),
              ),
              Expanded(
                child: Stack(
                  children: <Widget>[
                    _OneTimeOrderForm(state: state),
                    if (state.status == OneTimeOrderStatus.loading)
                      const Center(child: CircularProgressIndicator()),
                  ],
                ),
              ),
              _BottomActionButton(
                label: state.status == OneTimeOrderStatus.loading
                    ? labels.creating
                    : labels.create_order,
                isLoading: state.status == OneTimeOrderStatus.loading,
                onPressed: state.isValid
                    ? () => BlocProvider.of<OneTimeOrderBloc>(
                          context,
                        ).add(const OneTimeOrderSubmitted())
                    : null,
              ),
            ],
          ),
        );
      },
    );
  }
}

class _OneTimeOrderForm extends StatelessWidget {
  const _OneTimeOrderForm({required this.state});
  final OneTimeOrderState state;

  @override
  Widget build(BuildContext context) {
    final TranslationsClientCreateOrderOneTimeEn labels =
        t.client_create_order.one_time;

    return ListView(
      padding: const EdgeInsets.all(UiConstants.space5),
      children: <Widget>[
        Text(
          labels.create_your_order,
          style: UiTypography.headline3m.textPrimary,
        ),
        const SizedBox(height: UiConstants.space4),

        OneTimeOrderEventNameInput(
          label: 'ORDER NAME',
          value: state.eventName,
          onChanged: (String value) => BlocProvider.of<OneTimeOrderBloc>(
            context,
          ).add(OneTimeOrderEventNameChanged(value)),
        ),
        const SizedBox(height: UiConstants.space4),

        // Vendor Selection
        Text('SELECT VENDOR', style: UiTypography.footnote2r.textSecondary),
        const SizedBox(height: UiConstants.space2),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
          height: 48,
          decoration: BoxDecoration(
            color: UiColors.white,
            borderRadius: UiConstants.radiusMd,
            border: Border.all(color: UiColors.border),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<Vendor>(
              isExpanded: true,
              value: state.selectedVendor,
              icon: const Icon(
                UiIcons.chevronDown,
                size: 18,
                color: UiColors.iconSecondary,
              ),
              onChanged: (Vendor? vendor) {
                if (vendor != null) {
                  BlocProvider.of<OneTimeOrderBloc>(
                    context,
                  ).add(OneTimeOrderVendorChanged(vendor));
                }
              },
              items: state.vendors.map((Vendor vendor) {
                return DropdownMenuItem<Vendor>(
                  value: vendor,
                  child: Text(
                    vendor.name,
                    style: UiTypography.body2m.textPrimary,
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        const SizedBox(height: UiConstants.space4),

        OneTimeOrderDatePicker(
          label: labels.date_label,
          value: state.date,
          onChanged: (DateTime date) => BlocProvider.of<OneTimeOrderBloc>(
            context,
          ).add(OneTimeOrderDateChanged(date)),
        ),
        const SizedBox(height: UiConstants.space4),

        Text('HUB', style: UiTypography.footnote2r.textSecondary),
        const SizedBox(height: UiConstants.space2),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
          height: 48,
          decoration: BoxDecoration(
            color: UiColors.white,
            borderRadius: UiConstants.radiusMd,
            border: Border.all(color: UiColors.border),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<OneTimeOrderHubOption>(
              isExpanded: true,
              value: state.selectedHub,
              icon: const Icon(
                UiIcons.chevronDown,
                size: 18,
                color: UiColors.iconSecondary,
              ),
              onChanged: (OneTimeOrderHubOption? hub) {
                if (hub != null) {
                  BlocProvider.of<OneTimeOrderBloc>(
                    context,
                  ).add(OneTimeOrderHubChanged(hub));
                }
              },
              items: state.hubs.map((OneTimeOrderHubOption hub) {
                return DropdownMenuItem<OneTimeOrderHubOption>(
                  value: hub,
                  child: Text(
                    hub.name,
                    style: UiTypography.body2m.textPrimary,
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        const SizedBox(height: UiConstants.space6),

        OneTimeOrderSectionHeader(
          title: labels.positions_title,
          actionLabel: labels.add_position,
          onAction: () => BlocProvider.of<OneTimeOrderBloc>(
            context,
          ).add(const OneTimeOrderPositionAdded()),
        ),
        const SizedBox(height: UiConstants.space3),

        // Positions List
        ...state.positions.asMap().entries.map((
          MapEntry<int, OneTimeOrderPosition> entry,
        ) {
          final int index = entry.key;
          final OneTimeOrderPosition position = entry.value;
          return Padding(
            padding: const EdgeInsets.only(bottom: UiConstants.space3),
            child: OneTimeOrderPositionCard(
              index: index,
              position: position,
              isRemovable: state.positions.length > 1,
              positionLabel: labels.positions_title,
              roleLabel: labels.select_role,
              workersLabel: labels.workers_label,
              startLabel: labels.start_label,
              endLabel: labels.end_label,
              lunchLabel: labels.lunch_break_label,
              roles: state.roles,
              onUpdated: (OneTimeOrderPosition updated) {
                BlocProvider.of<OneTimeOrderBloc>(
                  context,
                ).add(OneTimeOrderPositionUpdated(index, updated));
              },
              onRemoved: () {
                BlocProvider.of<OneTimeOrderBloc>(
                  context,
                ).add(OneTimeOrderPositionRemoved(index));
              },
            ),
          );
        }),
      ],
    );
  }
}

class _BottomActionButton extends StatelessWidget {
  const _BottomActionButton({
    required this.label,
    required this.onPressed,
    this.isLoading = false,
  });
  final String label;
  final VoidCallback? onPressed;
  final bool isLoading;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        left: UiConstants.space5,
        right: UiConstants.space5,
        top: UiConstants.space5,
        bottom: MediaQuery.of(context).padding.bottom + UiConstants.space5,
      ),
      decoration: const BoxDecoration(
        color: UiColors.white,
        border: Border(top: BorderSide(color: UiColors.border)),
      ),
      child: SizedBox(
        width: double.infinity,
        child: UiButton.primary(
          text: label,
          onPressed: isLoading ? null : onPressed,
          size: UiButtonSize.large,
        ),
      ),
    );
  }
}
