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

import '../bloc/clock_in_bloc.dart';
import '../bloc/clock_in_event.dart';
import '../bloc/clock_in_state.dart';
import '../widgets/commute_tracker.dart';
import '../widgets/date_selector.dart';
import '../widgets/lunch_break_modal.dart';
import '../widgets/swipe_to_check_in.dart';

class ClockInPage extends StatefulWidget {
  const ClockInPage({super.key});

  @override
  State<ClockInPage> createState() => _ClockInPageState();
}

class _ClockInPageState extends State<ClockInPage> {
  late final ClockInBloc _bloc;

  @override
  void initState() {
    super.initState();
    _bloc = Modular.get<ClockInBloc>();
  }

  @override
  Widget build(BuildContext context) {
    final i18n = Translations.of(context).staff.clock_in;
    return BlocProvider<ClockInBloc>.value(
      value: _bloc,
      child: BlocConsumer<ClockInBloc, ClockInState>(
        listener: (BuildContext context, ClockInState state) {
          if (state.status == ClockInStatus.failure &&
              state.errorMessage != null) {
            UiSnackbar.show(
              context,
              message: translateErrorKey(state.errorMessage!),
              type: UiSnackbarType.error,
            );
          }
        },
        builder: (BuildContext context, ClockInState state) {
          if (state.status == ClockInStatus.loading &&
              state.todayShifts.isEmpty) {
            return const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          final List<Shift> todayShifts = state.todayShifts;
          final Shift? selectedShift = state.selectedShift;
          final String? activeShiftId = state.attendance.activeShiftId;
          final bool isActiveSelected =
              selectedShift != null && selectedShift.id == activeShiftId;
          final DateTime? checkInTime =
              isActiveSelected ? state.attendance.checkInTime : null;
          final DateTime? checkOutTime =
              isActiveSelected ? state.attendance.checkOutTime : null;
          final bool isCheckedIn =
              state.attendance.isCheckedIn && isActiveSelected;

          return Scaffold(
            appBar: UiAppBar(
              titleWidget: Text(
                i18n.title,
                style: UiTypography.title1m.textPrimary,
              ),
              showBackButton: false,
              centerTitle: false,
            ),
            body: SafeArea(
              child: SingleChildScrollView(
                padding: const EdgeInsets.only(
                  bottom: UiConstants.space24,
                  top: UiConstants.space6,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: UiConstants.space5,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          // Commute Tracker (shows before date selector when applicable)
                          if (selectedShift != null)
                            CommuteTracker(
                              shift: selectedShift,
                              hasLocationConsent: state.hasLocationConsent,
                              isCommuteModeOn: state.isCommuteModeOn,
                              distanceMeters: state.distanceFromVenue,
                              etaMinutes: state.etaMinutes,
                              onCommuteToggled: (bool value) {
                                _bloc.add(CommuteModeToggled(value));
                              },
                            ),
                          // Date Selector
                          DateSelector(
                            selectedDate: state.selectedDate,
                            onSelect: (DateTime date) =>
                                _bloc.add(DateSelected(date)),
                            shiftDates: <String>[
                              DateFormat('yyyy-MM-dd').format(DateTime.now()),
                            ],
                          ),
                          const SizedBox(height: UiConstants.space5),

                          // Your Activity Header
                          Text(
                            i18n.your_activity,
                            textAlign: TextAlign.start,
                            style: UiTypography.headline4m,
                          ),

                          const SizedBox(height: UiConstants.space4),

                          // Selected Shift Info Card
                          if (todayShifts.isNotEmpty)
                            Column(
                              children: todayShifts
                                  .map(
                                    (Shift shift) => GestureDetector(
                                      onTap: () =>
                                          _bloc.add(ShiftSelected(shift)),
                                      child: Container(
                                        padding: const EdgeInsets.all(
                                          UiConstants.space3,
                                        ),
                                        margin: const EdgeInsets.only(
                                          bottom: UiConstants.space3,
                                        ),
                                        decoration: BoxDecoration(
                                          color: UiColors.white,
                                          borderRadius:
                                                UiConstants.radiusLg,
                                          border: Border.all(
                                            color: shift.id ==
                                                    selectedShift?.id
                                                ? UiColors.primary
                                                : UiColors.border,
                                            width:
                                                shift.id == selectedShift?.id
                                                    ? 2
                                                    : 1,
                                          ),
                                        ),
                                        child: Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                    Text(
                                                      shift.id ==
                                                              selectedShift?.id
                                                          ? i18n
                                                              .selected_shift_badge
                                                          : i18n
                                                              .today_shift_badge,
                                                      style: UiTypography
                                                          .titleUppercase4b
                                                          .copyWith(
                                                        color: shift.id ==
                                                                selectedShift?.id
                                                            ? UiColors.primary
                                                            : UiColors
                                                                .textSecondary,
                                                      ),
                                                    ),
                                                  const SizedBox(height: 2),
                                                  Text(
                                                    shift.title,
                                                    style: UiTypography.body2b,
                                                  ),
                                                  Text(
                                                    "${shift.clientName} • ${shift.location}",
                                                    style: UiTypography.body3r
                                                        .textSecondary,
                                                  ),
                                                ],
                                              ),
                                            ),
                                            Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.end,
                                              children: <Widget>[
                                                Text(
                                                  "${_formatTime(shift.startTime)} - ${_formatTime(shift.endTime)}",
                                                  style: UiTypography.body3m
                                                      .textSecondary,
                                                ),
                                                Text(
                                                  "\$${shift.hourlyRate}/hr",
                                                  style: UiTypography.body3m
                                                      .copyWith(
                                                    color: UiColors.primary,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                            ),

                          // Swipe To Check In / Checked Out State / No Shift State
                          if (selectedShift != null &&
                              checkOutTime == null) ...<Widget>[
                            if (!isCheckedIn &&
                                !_isCheckInAllowed(selectedShift))
                              Container(
                                width: double.infinity,
                                padding:
                                    const EdgeInsets.all(UiConstants.space6),
                                decoration: BoxDecoration(
                                  color: UiColors.bgSecondary,
                                  borderRadius: UiConstants.radiusLg,
                                ),
                                child: Column(
                                  children: <Widget>[
                                    const Icon(
                                      UiIcons.clock,
                                      size: 48,
                                      color: UiColors.iconThird,
                                    ),
                                    const SizedBox(height: UiConstants.space4),
                                    Text(
                                      i18n.early_title,
                                      style: UiTypography.body1m.textSecondary,
                                    ),
                                    const SizedBox(height: UiConstants.space1),
                                    Text(
                                      i18n.check_in_at(
                                        time: _getCheckInAvailabilityTime(
                                          selectedShift,
                                        ),
                                      ),
                                      style: UiTypography.body2r.textSecondary,
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              )
                            else
                              SwipeToCheckIn(
                                isCheckedIn: isCheckedIn,
                                mode: state.checkInMode,
                                isLoading:
                                    state.status ==
                                    ClockInStatus.actionInProgress,
                                onCheckIn: () async {
                                  // Show NFC dialog if mode is 'nfc'
                                  if (state.checkInMode == 'nfc') {
                                    await _showNFCDialog(context);
                                  } else {
                                    _bloc.add(
                                      CheckInRequested(
                                        shiftId: selectedShift.id,
                                      ),
                                    );
                                  }
                                },
                                onCheckOut: () {
                                  showDialog(
                                    context: context,
                                    builder: (BuildContext context) =>
                                        LunchBreakDialog(
                                          onComplete: () {
                                            Navigator.of(
                                              context,
                                            ).pop(); // Close dialog first
                                            _bloc.add(
                                              const CheckOutRequested(),
                                            );
                                          },
                                        ),
                                  );
                                },
                              ),
                          ] else if (selectedShift != null &&
                              checkOutTime != null) ...<Widget>[
                            // Shift Completed State
                            Container(
                              padding: const EdgeInsets.all(UiConstants.space6),
                              decoration: BoxDecoration(
                                color: UiColors.tagSuccess,
                                borderRadius: UiConstants.radiusLg,
                                border: Border.all(
                                  color: UiColors.success.withValues(
                                    alpha: 0.3,
                                  ),
                                ),
                              ),
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    width: 48,
                                    height: 48,
                                    decoration: const BoxDecoration(
                                      color: UiColors.tagActive,
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Icon(
                                      UiIcons.check,
                                      color: UiColors.textSuccess,
                                      size: 24,
                                    ),
                                  ),
                                  const SizedBox(height: UiConstants.space3),
                                  Text(
                                    i18n.shift_completed,
                                    style: UiTypography.body1b.textSuccess,
                                  ),
                                  const SizedBox(height: UiConstants.space1),
                                  Text(
                                    i18n.great_work,
                                    style: UiTypography.body2r.textSuccess,
                                  ),
                                ],
                              ),
                            ),
                          ] else ...<Widget>[
                            // No Shift State
                            Container(
                              width: double.infinity,
                              padding: const EdgeInsets.all(UiConstants.space6),
                              decoration: BoxDecoration(
                                color: UiColors.bgSecondary,
                                borderRadius: UiConstants.radiusLg,
                              ),
                              child: Column(
                                children: <Widget>[
                                  Text(
                                    i18n.no_shifts_today,
                                    style: UiTypography.body1m.textSecondary,
                                    textAlign: TextAlign.center,
                                  ),
                                  const SizedBox(height: UiConstants.space1),
                                  Text(
                                    i18n.accept_shift_cta,
                                    style: UiTypography.body2r.textSecondary,
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            ),
                          ],

                          // Checked In Banner
                          if (isCheckedIn && checkInTime != null) ...<Widget>[
                            const SizedBox(height: UiConstants.space3),
                            Container(
                              padding: const EdgeInsets.all(UiConstants.space3),
                              decoration: BoxDecoration(
                                color: UiColors.tagSuccess,
                                borderRadius: UiConstants.radiusLg,
                                border: Border.all(
                                  color: UiColors.success.withValues(
                                    alpha: 0.3,
                                  ),
                                ),
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        i18n.checked_in_at_label,
                                        style: UiTypography.body3m.textSuccess,
                                      ),
                                      Text(
                                        DateFormat(
                                          'h:mm a',
                                        ).format(checkInTime),
                                        style: UiTypography.body1b.textSuccess,
                                      ),
                                    ],
                                  ),
                                  Container(
                                    width: 40,
                                    height: 40,
                                    decoration: const BoxDecoration(
                                      color: UiColors.tagActive,
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Icon(
                                      UiIcons.check,
                                      color: UiColors.textSuccess,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],

                          const SizedBox(height: 16),

                          // Recent Activity List (Temporarily removed)
                          const SizedBox(height: 16),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildModeTab(
    String label,
    IconData icon,
    String value,
    String currentMode,
  ) {
    final bool isSelected = currentMode == value;
    return Expanded(
      child: GestureDetector(
        onTap: () => _bloc.add(CheckInModeChanged(value)),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: UiConstants.space2),
          decoration: BoxDecoration(
            color: isSelected ? UiColors.white : UiColors.transparent,
            borderRadius: UiConstants.radiusMd,
            boxShadow: isSelected
                ? <BoxShadow>[
                    BoxShadow(
                      color: UiColors.black.withValues(alpha: 0.05),
                      blurRadius: 2,
                      offset: const Offset(0, 1),
                    ),
                  ]
                : <BoxShadow>[],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(
                icon,
                size: 16,
                color: isSelected ? UiColors.foreground : UiColors.iconThird,
              ),
              const SizedBox(width: 6),
              Text(
                label,
                style: UiTypography.body2m.copyWith(
                  color: isSelected
                      ? UiColors.foreground
                      : UiColors.textSecondary,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _showNFCDialog(BuildContext context) async {
    final i18n = Translations.of(context).staff.clock_in;
    bool scanned = false;

    // Using a local navigator context since we are in a dialog
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext dialogContext) {
        return StatefulBuilder(
          builder: (BuildContext context, setState) {
            return AlertDialog(
              title: Text(
                scanned
                    ? i18n.nfc_dialog.scanned_title
                    : i18n.nfc_dialog.scan_title,
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    width: 96,
                    height: 96,
                    decoration: BoxDecoration(
                      color: scanned
                          ? UiColors.tagSuccess
                          : UiColors.tagInProgress,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      scanned ? UiIcons.check : UiIcons.nfc,
                      size: 48,
                      color: scanned ? UiColors.textSuccess : UiColors.primary,
                    ),
                  ),
                  const SizedBox(height: UiConstants.space6),
                  Text(
                    scanned
                        ? i18n.nfc_dialog.processing
                        : i18n.nfc_dialog.ready_to_scan,
                    style: UiTypography.headline4m,
                  ),
                  const SizedBox(height: UiConstants.space2),
                  Text(
                    scanned
                        ? i18n.nfc_dialog.please_wait
                        : i18n.nfc_dialog.scan_instruction,
                    textAlign: TextAlign.center,
                    style: UiTypography.body2r.textSecondary,
                  ),
                  if (!scanned) ...<Widget>[
                    const SizedBox(height: UiConstants.space6),
                    SizedBox(
                      width: double.infinity,
                      height: 56,
                      child: ElevatedButton.icon(
                        onPressed: () async {
                          setState(() {
                            scanned = true;
                          });
                          // Simulate NFC scan delay
                          await Future.delayed(
                            const Duration(milliseconds: 1000),
                          );
                          if (!context.mounted) return;
                          Navigator.of(dialogContext).pop();
                          // Trigger BLoC event
                          // Need to access the bloc from the outer context or via passed reference
                          // Since _bloc is a field of the page state, we can use it if we are inside the page class
                          // But this dialog is just a function call.
                          // It's safer to just return a result
                        },
                        icon: const Icon(UiIcons.nfc, size: 24),
                        label: Text(
                          i18n.nfc_dialog.tap_to_scan,
                          style: UiTypography.headline4m.white,
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: UiColors.primary,
                          foregroundColor: UiColors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: UiConstants.radiusLg,
                          ),
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            );
          },
        );
      },
    );

    // After dialog closes, trigger the event if scan was successful (simulated)
    // In real app, we would check the dialog result
    if (scanned && _bloc.state.selectedShift != null) {
      _bloc.add(CheckInRequested(shiftId: _bloc.state.selectedShift!.id));
    }
  }

  // --- Helper Methods ---

  String _formatTime(String timeStr) {
    if (timeStr.isEmpty) return '';
    try {
      // Try parsing as ISO string first (which contains date)
      final DateTime dt = DateTime.parse(timeStr);
      return DateFormat('h:mm a').format(dt);
    } catch (_) {
      // Fallback for strict "HH:mm" or "HH:mm:ss" strings
      try {
        final List<String> parts = timeStr.split(':');
        if (parts.length >= 2) {
           final DateTime dt = DateTime(2022, 1, 1, int.parse(parts[0]), int.parse(parts[1]));
           return DateFormat('h:mm a').format(dt);
        }
        return timeStr;
      } catch (e) {
        return timeStr;
      }
    }
  }

  bool _isCheckInAllowed(Shift shift) {
    try {
      // Parse shift date (e.g. 2024-01-31T09:00:00)
      // The Shift entity has 'date' which is the start DateTime string
      final DateTime shiftStart = DateTime.parse(shift.startTime);
      final DateTime windowStart = shiftStart.subtract(const Duration(minutes: 15));
      return DateTime.now().isAfter(windowStart);
    } catch (e) {
      // Fallback: If parsing fails, allow check in to avoid blocking.
      return true;
    }
  }

  String _getCheckInAvailabilityTime(Shift shift) {
     try {
       final DateTime shiftStart = DateTime.parse(shift.startTime.trim());
       final DateTime windowStart = shiftStart.subtract(const Duration(minutes: 15));
       return DateFormat('h:mm a').format(windowStart);
     } catch (e) {
       final i18n = Translations.of(context).staff.clock_in;
       return i18n.soon;
     }
  }
}
