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 'package:krow_domain/krow_domain.dart';

import '../blocs/shift_details/shift_details_bloc.dart';
import '../blocs/shift_details/shift_details_event.dart';
import '../blocs/shift_details/shift_details_state.dart';
import '../widgets/shift_details/shift_break_section.dart';
import '../widgets/shift_details/shift_date_time_section.dart';
import '../widgets/shift_details/shift_description_section.dart';
import '../widgets/shift_details/shift_details_bottom_bar.dart';
import '../widgets/shift_details/shift_details_header.dart';
import '../widgets/shift_details/shift_location_section.dart';
import '../widgets/shift_details/shift_stats_row.dart';

class ShiftDetailsPage extends StatefulWidget {
  final String shiftId;
  final Shift shift;

  const ShiftDetailsPage({
    super.key,
    required this.shiftId,
    required this.shift,
  });

  @override
  State<ShiftDetailsPage> createState() => _ShiftDetailsPageState();
}

class _ShiftDetailsPageState extends State<ShiftDetailsPage> {
  bool _actionDialogOpen = false;
  bool _isApplying = false;

  String _formatTime(String time) {
    if (time.isEmpty) return '';
    try {
      final parts = time.split(':');
      final hour = int.parse(parts[0]);
      final minute = int.parse(parts[1]);
      final dt = DateTime(2022, 1, 1, hour, minute);
      return DateFormat('h:mm a').format(dt);
    } catch (e) {
      return time;
    }
  }

  String _formatDate(String dateStr) {
    if (dateStr.isEmpty) return '';
    try {
      final date = DateTime.parse(dateStr);
      return DateFormat('EEEE, MMMM d, y').format(date);
    } catch (e) {
      return dateStr;
    }
  }

  double _calculateDuration(Shift shift) {
    if (shift.startTime.isEmpty || shift.endTime.isEmpty) {
      return 0;
    }
    try {
      final s = shift.startTime.split(':').map(int.parse).toList();
      final e = shift.endTime.split(':').map(int.parse).toList();
      double hours = ((e[0] * 60 + e[1]) - (s[0] * 60 + s[1])) / 60;
      if (hours < 0) hours += 24;
      return hours.roundToDouble();
    } catch (_) {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ShiftDetailsBloc>(
      create: (_) => Modular.get<ShiftDetailsBloc>()
        ..add(
          LoadShiftDetailsEvent(widget.shiftId, roleId: widget.shift.roleId),
        ),
      child: BlocConsumer<ShiftDetailsBloc, ShiftDetailsState>(
        listener: (context, state) {
          if (state is ShiftActionSuccess || state is ShiftDetailsError) {
            _closeActionDialog(context);
          }
          if (state is ShiftActionSuccess) {
            _isApplying = false;
            UiSnackbar.show(
              context,
              message: state.message,
              type: UiSnackbarType.success,
            );
            Modular.to.toShifts(selectedDate: state.shiftDate);
          } else if (state is ShiftDetailsError) {
            if (_isApplying) {
              UiSnackbar.show(
                context,
                message: translateErrorKey(state.message),
                type: UiSnackbarType.error,
              );
            }
            _isApplying = false;
          }
        },
        builder: (context, state) {
          if (state is ShiftDetailsLoading) {
            return const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          Shift displayShift = widget.shift;
          final i18n = Translations.of(context).staff_shifts.shift_details;

          final duration = _calculateDuration(displayShift);
          final estimatedTotal =
              displayShift.totalValue ?? (displayShift.hourlyRate * duration);

          return Scaffold(
            appBar: UiAppBar(
              centerTitle: false,
              onLeadingPressed: () => Modular.to.toShifts(),
            ),
            body: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ShiftDetailsHeader(shift: displayShift),
                        const Divider(height: 1, thickness: 0.5),
                        ShiftStatsRow(
                          estimatedTotal: estimatedTotal,
                          hourlyRate: displayShift.hourlyRate,
                          duration: duration,
                          totalLabel: i18n.est_total,
                          hourlyRateLabel: i18n.hourly_rate,
                          hoursLabel: i18n.hours,
                        ),
                        const Divider(height: 1, thickness: 0.5),
                        ShiftDateTimeSection(
                          date: displayShift.date,
                          startTime: displayShift.startTime,
                          endTime: displayShift.endTime,
                          shiftDateLabel: i18n.shift_date,
                          clockInLabel: i18n.start_time,
                          clockOutLabel: i18n.end_time,
                        ),
                        const Divider(height: 1, thickness: 0.5),
                        if (displayShift.breakInfo != null &&
                            displayShift.breakInfo!.duration !=
                                BreakDuration.none) ...[
                          ShiftBreakSection(
                            breakInfo: displayShift.breakInfo!,
                            breakTitle: i18n.break_title,
                            paidLabel: i18n.paid,
                            unpaidLabel: i18n.unpaid,
                            minLabel: i18n.min,
                          ),
                          const Divider(height: 1, thickness: 0.5),
                        ],
                        ShiftLocationSection(
                          shift: displayShift,
                          locationLabel: i18n.location,
                          tbdLabel: i18n.tbd,
                          getDirectionLabel: i18n.get_direction,
                        ),
                        const Divider(height: 1, thickness: 0.5),
                        if (displayShift.description != null &&
                            displayShift.description!.isNotEmpty)
                          ShiftDescriptionSection(
                            description: displayShift.description!,
                            descriptionLabel: i18n.job_description,
                          ),
                      ],
                    ),
                  ),
                ),
                ShiftDetailsBottomBar(
                  shift: displayShift,
                  onApply: () => _bookShift(context, displayShift),
                  onDecline: () => BlocProvider.of<ShiftDetailsBloc>(
                    context,
                  ).add(DeclineShiftDetailsEvent(displayShift.id)),
                  onAccept: () =>
                      BlocProvider.of<ShiftDetailsBloc>(context).add(
                        BookShiftDetailsEvent(
                          displayShift.id,
                          roleId: displayShift.roleId,
                        ),
                      ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  void _bookShift(BuildContext context, Shift shift) {
    final i18n = Translations.of(
      context,
    ).staff_shifts.shift_details.book_dialog;
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(i18n.title),
        content: Text(i18n.message),
        actions: [
          TextButton(
            onPressed: () => Modular.to.pop(),
            child: Text(Translations.of(context).common.cancel),
          ),
          TextButton(
            onPressed: () {
              Modular.to.pop();
              _showApplyingDialog(context, shift);
              BlocProvider.of<ShiftDetailsBloc>(context).add(
                BookShiftDetailsEvent(
                  shift.id,
                  roleId: shift.roleId,
                  date: DateTime.tryParse(shift.date),
                ),
              );
            },
            style: TextButton.styleFrom(foregroundColor: UiColors.success),
            child: Text(
              Translations.of(context).staff_shifts.shift_details.apply_now,
            ),
          ),
        ],
      ),
    );
  }

  void _showApplyingDialog(BuildContext context, Shift shift) {
    if (_actionDialogOpen) return;
    _actionDialogOpen = true;
    _isApplying = true;
    final i18n = Translations.of(
      context,
    ).staff_shifts.shift_details.applying_dialog;
    showDialog(
      context: context,
      useRootNavigator: true,
      barrierDismissible: false,
      builder: (ctx) => AlertDialog(
        title: Text(i18n.title),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(
              height: 36,
              width: 36,
              child: CircularProgressIndicator(),
            ),
            const SizedBox(height: UiConstants.space4),
            Text(
              shift.title,
              style: UiTypography.body2b.textPrimary,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 6),
            Text(
              '${_formatDate(shift.date)} • ${_formatTime(shift.startTime)} - ${_formatTime(shift.endTime)}',
              style: UiTypography.body3r.textSecondary,
              textAlign: TextAlign.center,
            ),
            if (shift.clientName.isNotEmpty) ...[
              const SizedBox(height: 6),
              Text(
                shift.clientName,
                style: UiTypography.body3r.textSecondary,
                textAlign: TextAlign.center,
              ),
            ],
          ],
        ),
      ),
    ).then((_) {
      _actionDialogOpen = false;
    });
  }

  void _closeActionDialog(BuildContext context) {
    if (!_actionDialogOpen) return;
    Navigator.of(context, rootNavigator: true).pop();
    _actionDialogOpen = false;
  }
}
