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

import '../bloc/clock_in_bloc.dart';
import '../bloc/clock_in_event.dart';
import '../bloc/clock_in_state.dart';
import '../theme/app_colors.dart';
import '../widgets/attendance_card.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) {
    return BlocProvider<ClockInBloc>.value(
      value: _bloc,
      child: BlocConsumer<ClockInBloc, ClockInState>(
        listener: (context, state) {
          if (state.status == ClockInStatus.failure &&
              state.errorMessage != null) {
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(SnackBar(content: Text(state.errorMessage!)));
          }
        },
        builder: (context, state) {
          if (state.status == ClockInStatus.loading &&
              state.todayShift == null) {
            return const Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          final todayShift = state.todayShift;
          final checkInTime = state.attendance.checkInTime;
          final checkOutTime = state.attendance.checkOutTime;
          final isCheckedIn = state.attendance.isCheckedIn;

          // Format times for display
          final checkInStr = checkInTime != null
              ? DateFormat('h:mm a').format(checkInTime)
              : '--:-- --';
          final checkOutStr = checkOutTime != null
              ? DateFormat('h:mm a').format(checkOutTime)
              : '--:-- --';

          return Scaffold(
            appBar: UiAppBar(
              titleWidget: Text(
                'Clock In to your Shift',
                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: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // Commute Tracker (shows before date selector when applicable)
                          if (todayShift != null)
                            CommuteTracker(
                              shift: todayShift,
                              hasLocationConsent: state.hasLocationConsent,
                              isCommuteModeOn: state.isCommuteModeOn,
                              distanceMeters: state.distanceFromVenue,
                              etaMinutes: state.etaMinutes,
                              onCommuteToggled: (value) {
                                _bloc.add(CommuteModeToggled(value));
                              },
                            ),
                          // Date Selector
                          DateSelector(
                            selectedDate: state.selectedDate,
                            onSelect: (date) => _bloc.add(DateSelected(date)),
                            shiftDates: [
                              DateFormat('yyyy-MM-dd').format(DateTime.now()),
                            ],
                          ),
                          const SizedBox(height: 20),


                          // Your Activity Header
                          const Text(
                            "Your Activity",
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: AppColors.krowCharcoal,
                            ),
                          ),

                          const SizedBox(height: 16),

                          // Selected Shift Info Card
                          if (todayShift != null)
                            Container(
                              padding: const EdgeInsets.all(12),
                              margin: const EdgeInsets.only(bottom: 16),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: const Color(0xFFE2E8F0),
                                ), // slate-200
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.05),
                                    blurRadius: 2,
                                    offset: const Offset(0, 1),
                                  ),
                                ],
                              ),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const Text(
                                          "TODAY'S SHIFT",
                                          style: TextStyle(
                                            fontSize: 10,
                                            fontWeight: FontWeight.w600,
                                            color: AppColors.krowBlue,
                                            letterSpacing: 0.5,
                                          ),
                                        ),
                                        const SizedBox(height: 2),
                                        Text(
                                          todayShift.title,
                                          style: const TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w600,
                                            color: Color(
                                              0xFF1E293B,
                                            ), // slate-800
                                          ),
                                        ),
                                        Text(
                                          "${todayShift.clientName} • ${todayShift.location}",
                                          style: const TextStyle(
                                            fontSize: 12,
                                            color: Color(
                                              0xFF64748B,
                                            ), // slate-500
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Text(
                                        "${_formatTime(todayShift.startTime)} - ${_formatTime(todayShift.endTime)}",
                                        style: const TextStyle(
                                          fontSize: 12,
                                          fontWeight: FontWeight.w500,
                                          color: Color(0xFF475569), // slate-600
                                        ),
                                      ),
                                      Text(
                                        "\$${todayShift.hourlyRate}/hr",
                                        style: const TextStyle(
                                          fontSize: 12,
                                          fontWeight: FontWeight.w600,
                                          color: AppColors.krowBlue,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),

                          // Swipe To Check In / Checked Out State / No Shift State
                          if (todayShift != null && checkOutTime == null) ...[
                             if (!isCheckedIn && !_isCheckInAllowed(todayShift))
                               Container(
                                 width: double.infinity,
                                 padding: const EdgeInsets.all(24),
                                 decoration: BoxDecoration(
                                   color: const Color(0xFFF1F5F9), // slate-100
                                   borderRadius: BorderRadius.circular(16),
                                 ),
                                 child: Column(
                                   children: [
                                     const Icon(
                                       LucideIcons.clock,
                                       size: 48,
                                       color: Color(0xFF94A3B8), // slate-400
                                     ),
                                     const SizedBox(height: 16),
                                     const Text(
                                       "You're early!",
                                       style: TextStyle(
                                         fontSize: 16,
                                         fontWeight: FontWeight.w600,
                                         color: Color(0xFF475569), // slate-600
                                       ),
                                     ),
                                     const SizedBox(height: 4),
                                     Text(
                                       "Check-in available at ${_getCheckInAvailabilityTime(todayShift)}",
                                       style: const TextStyle(
                                         fontSize: 14,
                                         color: Color(0xFF64748B), // slate-500
                                       ),
                                       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: todayShift.id),
                                    );
                                  }
                                },
                                onCheckOut: () {
                                  showDialog(
                                    context: context,
                                    builder: (context) => LunchBreakDialog(
                                      onComplete: () {
                                        Navigator.of(
                                          context,
                                        ).pop(); // Close dialog first
                                        _bloc.add(const CheckOutRequested());
                                      },
                                    ),
                                  );
                                },
                              ),
                          ] else if (todayShift != null &&
                              checkOutTime != null) ...[
                            // Shift Completed State
                            Container(
                              padding: const EdgeInsets.all(24),
                              decoration: BoxDecoration(
                                color: const Color(0xFFECFDF5), // emerald-50
                                borderRadius: BorderRadius.circular(16),
                                border: Border.all(
                                  color: const Color(0xFFA7F3D0),
                                ), // emerald-200
                              ),
                              child: Column(
                                children: [
                                  Container(
                                    width: 48,
                                    height: 48,
                                    decoration: const BoxDecoration(
                                      color: Color(0xFFD1FAE5), // emerald-100
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Icon(
                                      LucideIcons.check,
                                      color: Color(0xFF059669), // emerald-600
                                      size: 24,
                                    ),
                                  ),
                                  const SizedBox(height: 12),
                                  const Text(
                                    "Shift Completed!",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xFF065F46), // emerald-800
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  const Text(
                                    "Great work today",
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Color(0xFF059669), // emerald-600
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ] else ...[
                            // No Shift State
                            Container(
                              width: double.infinity,
                              padding: const EdgeInsets.all(24),
                              decoration: BoxDecoration(
                                color: const Color(0xFFF1F5F9), // slate-100
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: const Column(
                                children: [
                                  const Text(
                                    "No confirmed shifts for today",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      color: Color(0xFF475569), // slate-600
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                  const SizedBox(height: 4),
                                  const Text(
                                    "Accept a shift to clock in",
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Color(0xFF64748B), // slate-500
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            ),
                          ],

                          // Checked In Banner
                          if (isCheckedIn && checkInTime != null) ...[
                            const SizedBox(height: 12),
                            Container(
                              padding: const EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                color: const Color(0xFFECFDF5), // emerald-50
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: const Color(0xFFA7F3D0),
                                ), // emerald-200
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      const Text(
                                        "Checked in at",
                                        style: TextStyle(
                                          fontSize: 12,
                                          fontWeight: FontWeight.w500,
                                          color: Color(0xFF059669),
                                        ),
                                      ),
                                      Text(
                                        DateFormat(
                                          'h:mm a',
                                        ).format(checkInTime),
                                        style: const TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          color: Color(0xFF065F46),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    width: 40,
                                    height: 40,
                                    decoration: const BoxDecoration(
                                      color: Color(0xFFD1FAE5),
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Icon(
                                      LucideIcons.check,
                                      color: Color(0xFF059669),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],

                          const SizedBox(height: 16),

                          // Recent Activity List
                          if (state.activityLog.isNotEmpty)
                            ...state.activityLog.map(
                              (activity) => Container(
                                margin: const EdgeInsets.only(bottom: 12),
                                padding: const EdgeInsets.all(12),
                                decoration: BoxDecoration(
                                  color: const Color(0xFFF8F9FA),
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(
                                    color: const Color(0xFFF1F5F9),
                                  ), // slate-100
                                ),
                                child: Row(
                                  children: [
                                    Container(
                                      width: 40,
                                      height: 40,
                                      decoration: BoxDecoration(
                                        color: AppColors.krowBlue.withOpacity(
                                          0.1,
                                        ),
                                        borderRadius: BorderRadius.circular(12),
                                      ),
                                      child: const Icon(
                                        LucideIcons.mapPin,
                                        color: AppColors.krowBlue,
                                        size: 20,
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            DateFormat('MMM d').format(
                                              activity['date'] as DateTime,
                                            ),
                                            style: const TextStyle(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w500,
                                              color: Color(
                                                0xFF0F172A,
                                              ), // slate-900
                                            ),
                                          ),
                                          Text(
                                            "${activity['start']} - ${activity['end']}",
                                            style: const TextStyle(
                                              fontSize: 12,
                                              color: Color(
                                                0xFF64748B,
                                              ), // slate-500
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    Text(
                                      activity['hours'] as String,
                                      style: const TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.w600,
                                        color: AppColors.krowBlue,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          const SizedBox(height: 16),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildModeTab(
    String label,
    IconData icon,
    String value,
    String currentMode,
  ) {
    final isSelected = currentMode == value;
    return Expanded(
      child: GestureDetector(
        onTap: () => _bloc.add(CheckInModeChanged(value)),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? Colors.white : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
            boxShadow: isSelected
                ? [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 2,
                      offset: const Offset(0, 1),
                    ),
                  ]
                : [],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                icon,
                size: 16,
                color: isSelected ? Colors.black : Colors.grey,
              ),
              const SizedBox(width: 6),
              Text(
                label,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: isSelected ? Colors.black : Colors.grey,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 24, 20, 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: AppColors.krowBlue.withOpacity(0.2),
                    width: 2,
                  ),
                ),
                child: CircleAvatar(
                  backgroundColor: AppColors.krowBlue.withOpacity(0.1),
                  child: const Text(
                    'K',
                    style: TextStyle(
                      color: AppColors.krowBlue,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Good Morning',
                    style: TextStyle(color: AppColors.krowMuted, fontSize: 12),
                  ),
                  Text(
                    'Krower',
                    style: TextStyle(
                      color: AppColors.krowCharcoal,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    'Warehouse Assistant',
                    style: TextStyle(color: AppColors.krowMuted, fontSize: 12),
                  ),
                ],
              ),
            ],
          ),
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(
                20,
              ), // Rounded full for this page per design
              border: Border.all(color: Colors.grey.shade100),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: const Icon(
              LucideIcons.bell,
              color: AppColors.krowMuted,
              size: 20,
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _showNFCDialog(BuildContext context) async {
    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: (context, setState) {
            return AlertDialog(
              title: Text(scanned ? 'Tag Scanned!' : 'Scan NFC Tag'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 96,
                    height: 96,
                    decoration: BoxDecoration(
                      color: scanned
                          ? Colors.green.shade50
                          : Colors.blue.shade50,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      scanned ? LucideIcons.check : LucideIcons.nfc,
                      size: 48,
                      color: scanned
                          ? Colors.green.shade600
                          : Colors.blue.shade600,
                    ),
                  ),
                  const SizedBox(height: 24),
                  Text(
                    scanned ? 'Processing check-in...' : 'Ready to scan',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    scanned
                        ? 'Please wait...'
                        : 'Hold your phone near the NFC tag at the clock-in station',
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
                  ),
                  if (!scanned) ...[
                    const SizedBox(height: 24),
                    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(LucideIcons.nfc, size: 24),
                        label: const Text(
                          'Tap to Scan',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF0047FF),
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            );
          },
        );
      },
    );

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

  // --- Helper Methods ---

  String _formatTime(String timeStr) {
    // Expecting HH:mm or HH:mm:ss
    try {
      if (timeStr.isEmpty) return '';
      final parts = timeStr.split(':');
      final dt = DateTime(2022, 1, 1, int.parse(parts[0]), int.parse(parts[1]));
      return DateFormat('h:mm a').format(dt);
    } catch (e) {
      return timeStr;
    }
  }

  bool _isCheckInAllowed(dynamic shift) {
    if (shift == null) return false;
    try {
      // Parse shift date (e.g. 2024-01-31T09:00:00)
      // The Shift entity has 'date' which is the start DateTime string
      final shiftStart = DateTime.parse(shift.date);
      final 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(dynamic shift) {
     if (shift == null) return '';
     try {
       final shiftStart = DateTime.parse(shift.date);
       final windowStart = shiftStart.subtract(const Duration(minutes: 15));
       return DateFormat('h:mm a').format(windowStart);
     } catch (e) {
       return 'soon';
     }
  }
}
