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:intl/intl.dart';
import 'package:krow_core/core.dart';
import '../../blocs/rapid_order_bloc.dart';
import '../../blocs/rapid_order_event.dart';
import '../../blocs/rapid_order_state.dart';
import 'rapid_order_example_card.dart';
import 'rapid_order_header.dart';
import 'rapid_order_success_view.dart';

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

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

    return BlocBuilder<RapidOrderBloc, RapidOrderState>(
      builder: (BuildContext context, RapidOrderState state) {
        if (state is RapidOrderSuccess) {
          return RapidOrderSuccessView(
            title: labels.success_title,
            message: labels.success_message,
            buttonLabel: labels.back_to_orders,
            onDone: () => Modular.to.navigate(ClientPaths.orders),
          );
        }

        return const _RapidOrderForm();
      },
    );
  }
}

class _RapidOrderForm extends StatefulWidget {
  const _RapidOrderForm();

  @override
  State<_RapidOrderForm> createState() => _RapidOrderFormState();
}

class _RapidOrderFormState extends State<_RapidOrderForm> {
  final TextEditingController _messageController = TextEditingController();

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final TranslationsClientCreateOrderRapidEn labels =
        t.client_create_order.rapid;
    final DateTime now = DateTime.now();
    final String dateStr = DateFormat('EEE, MMM dd, yyyy').format(now);
    final String timeStr = DateFormat('h:mm a').format(now);

    return BlocListener<RapidOrderBloc, RapidOrderState>(
      listener: (BuildContext context, RapidOrderState state) {
        if (state is RapidOrderInitial) {
          if (_messageController.text != state.message) {
            _messageController.text = state.message;
            _messageController.selection = TextSelection.fromPosition(
              TextPosition(offset: _messageController.text.length),
            );
          }
        } else if (state is RapidOrderFailure) {
          UiSnackbar.show(
            context,
            message: translateErrorKey(state.error),
            type: UiSnackbarType.error,
          );
        }
      },
      child: Scaffold(
        body: Column(
          children: <Widget>[
            RapidOrderHeader(
              title: labels.title,
              subtitle: labels.subtitle,
              date: dateStr,
              time: timeStr,
              onBack: () => Modular.to.navigate(ClientPaths.createOrder),
            ),

            // Content
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(UiConstants.space5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          labels.tell_us,
                          style: UiTypography.headline3m.textPrimary,
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: UiConstants.space2,
                            vertical: UiConstants.space1,
                          ),
                          decoration: BoxDecoration(
                            color: UiColors.destructive,
                            borderRadius: UiConstants.radiusSm,
                          ),
                          child: Text(
                            labels.urgent_badge,
                            style: UiTypography.footnote2b.copyWith(
                              color: UiColors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: UiConstants.space4),

                    // Main Card
                    Container(
                      padding: const EdgeInsets.all(UiConstants.space6),
                      decoration: BoxDecoration(
                        color: UiColors.white,
                        borderRadius: UiConstants.radiusLg,
                        border: Border.all(color: UiColors.border),
                      ),
                      child: BlocBuilder<RapidOrderBloc, RapidOrderState>(
                        builder: (BuildContext context, RapidOrderState state) {
                          final RapidOrderInitial? initialState =
                              state is RapidOrderInitial ? state : null;
                          final bool isSubmitting =
                              state is RapidOrderSubmitting;

                          return Column(
                            children: <Widget>[
                              // Icon
                              const _AnimatedZapIcon(),
                              const SizedBox(height: UiConstants.space4),
                              Text(
                                labels.need_staff,
                                style: UiTypography.headline2m.textPrimary,
                              ),
                              const SizedBox(height: UiConstants.space2),
                              Text(
                                labels.type_or_speak,
                                textAlign: TextAlign.center,
                                style: UiTypography.body2r.textSecondary,
                              ),
                              const SizedBox(height: UiConstants.space6),

                              // Examples
                              if (initialState != null)
                                ...initialState.examples.asMap().entries.map((
                                  MapEntry<int, String> entry,
                                ) {
                                  final int index = entry.key;
                                  final String example = entry.value;
                                  final bool isHighlighted = index == 0;

                                  return Padding(
                                    padding: const EdgeInsets.only(
                                      bottom: UiConstants.space2,
                                    ),
                                    child: RapidOrderExampleCard(
                                      example: example,
                                      isHighlighted: isHighlighted,
                                      label: labels.example,
                                      onTap: () =>
                                          BlocProvider.of<RapidOrderBloc>(
                                            context,
                                          ).add(
                                            RapidOrderExampleSelected(example),
                                          ),
                                    ),
                                  );
                                }),
                              const SizedBox(height: UiConstants.space4),

                              // Input
                              UiTextField(
                                controller: _messageController,
                                maxLines: 4,
                                onChanged: (String value) {
                                  BlocProvider.of<RapidOrderBloc>(
                                    context,
                                  ).add(RapidOrderMessageChanged(value));
                                },
                                hintText: labels.hint,
                              ),
                              const SizedBox(height: UiConstants.space4),

                              // Actions
                              _RapidOrderActions(
                                labels: labels,
                                isSubmitting: isSubmitting,
                                isListening: initialState?.isListening ?? false,
                                isMessageEmpty:
                                    initialState != null &&
                                    initialState.message.trim().isEmpty,
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _AnimatedZapIcon extends StatelessWidget {
  const _AnimatedZapIcon();

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 64,
      height: 64,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: <Color>[
            UiColors.destructive,
            UiColors.destructive.withValues(alpha: 0.85),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: UiConstants.radiusLg,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.destructive.withValues(alpha: 0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: const Icon(UiIcons.zap, color: UiColors.white, size: 32),
    );
  }
}

class _RapidOrderActions extends StatelessWidget {
  const _RapidOrderActions({
    required this.labels,
    required this.isSubmitting,
    required this.isListening,
    required this.isMessageEmpty,
  });
  final TranslationsClientCreateOrderRapidEn labels;
  final bool isSubmitting;
  final bool isListening;
  final bool isMessageEmpty;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          child: UiButton.secondary(
            text: isListening ? labels.listening : labels.speak,
            leadingIcon: UiIcons.bell, // Placeholder for mic
            onPressed: () => BlocProvider.of<RapidOrderBloc>(
              context,
            ).add(const RapidOrderVoiceToggled()),
            style: OutlinedButton.styleFrom(
              backgroundColor: isListening
                  ? UiColors.destructive.withValues(alpha: 0.05)
                  : null,
              side: isListening
                  ? const BorderSide(color: UiColors.destructive)
                  : null,
            ),
          ),
        ),
        const SizedBox(width: UiConstants.space3),
        Expanded(
          child: UiButton.primary(
            text: isSubmitting ? labels.sending : labels.send,
            trailingIcon: UiIcons.arrowRight,
            onPressed: isSubmitting || isMessageEmpty
                ? null
                : () {
                    print('RapidOrder send pressed');
                    BlocProvider.of<RapidOrderBloc>(
                      context,
                    ).add(const RapidOrderSubmitted());
                  },
          ),
        ),
      ],
    );
  }
}
