import 'package:flutter/material.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../theme/app_colors.dart';
import 'package:krow_domain/krow_domain.dart';

enum CommuteMode {
  lockedNoShift,
  needsConsent,
  preShiftCommuteAllowed,
  commuteModeActive,
  arrivedCanClockIn,
}

class CommuteTracker extends StatefulWidget {
  final Shift? shift;
  final Function(CommuteMode)? onModeChange;
  final ValueChanged<bool>? onCommuteToggled;
  final bool hasLocationConsent;
  final bool isCommuteModeOn;
  final double? distanceMeters;
  final int? etaMinutes;

  const CommuteTracker({
    super.key,
    this.shift,
    this.onModeChange,
    this.onCommuteToggled,
    this.hasLocationConsent = false,
    this.isCommuteModeOn = false,
    this.distanceMeters,
    this.etaMinutes,
  });

  @override
  State<CommuteTracker> createState() => _CommuteTrackerState();
}

class _CommuteTrackerState extends State<CommuteTracker> {
  bool _localHasConsent = false;
  bool _localIsCommuteOn = false;

  @override
  void initState() {
    super.initState();
    _localHasConsent = widget.hasLocationConsent;
    _localIsCommuteOn = widget.isCommuteModeOn;
  }

  @override
  void didUpdateWidget(CommuteTracker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isCommuteModeOn != oldWidget.isCommuteModeOn) {
      setState(() {
        _localIsCommuteOn = widget.isCommuteModeOn;
      });
    }
    if (widget.hasLocationConsent != oldWidget.hasLocationConsent) {
      setState(() {
        _localHasConsent = widget.hasLocationConsent;
      });
    }
  }

  CommuteMode _getAppMode() {
    if (widget.shift == null) return CommuteMode.lockedNoShift;

    // For demo purposes, check if we're within 24 hours of shift
    final now = DateTime.now();
    final shiftStart = DateTime.parse(
      '${widget.shift!.date} ${widget.shift!.startTime}',
    );
    final hoursUntilShift = shiftStart.difference(now).inHours;
    final inCommuteWindow = hoursUntilShift <= 24 && hoursUntilShift >= 0;

    if (_localIsCommuteOn) {
      // Check if arrived (mock: if distance < 200m)
      if (widget.distanceMeters != null && widget.distanceMeters! <= 200) {
        return CommuteMode.arrivedCanClockIn;
      }
      return CommuteMode.commuteModeActive;
    }

    if (inCommuteWindow) {
      return _localHasConsent
          ? CommuteMode.preShiftCommuteAllowed
          : CommuteMode.needsConsent;
    }

    return CommuteMode.lockedNoShift;
  }

  String _formatDistance(double meters) {
    final miles = meters / 1609.34;
    return miles < 0.1
        ? '${meters.round()} m'
        : '${miles.toStringAsFixed(1)} mi';
  }

  int _getMinutesUntilShift() {
    if (widget.shift == null) return 0;
    final now = DateTime.now();
    final shiftStart = DateTime.parse(
      '${widget.shift!.date} ${widget.shift!.startTime}',
    );
    return shiftStart.difference(now).inMinutes;
  }

  @override
  Widget build(BuildContext context) {
    final mode = _getAppMode();

    // Notify parent of mode change
    WidgetsBinding.instance.addPostFrameCallback((_) {
      widget.onModeChange?.call(mode);
    });

    switch (mode) {
      case CommuteMode.lockedNoShift:
        return const SizedBox.shrink();

      case CommuteMode.needsConsent:
        return _buildConsentCard();

      case CommuteMode.preShiftCommuteAllowed:
        return _buildPreShiftCard();

      case CommuteMode.commuteModeActive:
        return _buildActiveCommuteScreen();

      case CommuteMode.arrivedCanClockIn:
        return _buildArrivedCard();
    }
  }

  Widget _buildConsentCard() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFFEFF6FF), // blue-50
            Color(0xFFECFEFF), // cyan-50
          ],
        ),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 2,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 32,
                height: 32,
                decoration: const BoxDecoration(
                  color: Color(0xFF2563EB), // blue-600
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  LucideIcons.mapPin,
                  size: 16,
                  color: Colors.white,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Enable Commute Tracking?',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF0F172A), // slate-900
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Share location 1hr before shift so your manager can see you\'re on the way.',
                      style: TextStyle(
                        fontSize: 12,
                        color: Color(0xFF475569), // slate-600
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    setState(() => _localHasConsent = false);
                  },
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    side: const BorderSide(color: Color(0xFFE2E8F0)),
                  ),
                  child: const Text('Not Now', style: TextStyle(fontSize: 12)),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    setState(() => _localHasConsent = true);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF2563EB), // blue-600
                    padding: const EdgeInsets.symmetric(vertical: 8),
                  ),
                  child: const Text(
                    'Enable',
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPreShiftCard() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 2,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: const BoxDecoration(
              color: Color(0xFFF1F5F9), // slate-100
              shape: BoxShape.circle,
            ),
            child: const Icon(
              LucideIcons.navigation,
              size: 16,
              color: Color(0xFF475569), // slate-600
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Text(
                      'On My Way',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF0F172A), // slate-900
                      ),
                    ),
                    const SizedBox(width: 8),
                    Row(
                      children: [
                        const Icon(
                          LucideIcons.clock,
                          size: 12,
                          color: Color(0xFF64748B), // slate-500
                        ),
                        const SizedBox(width: 2),
                        Text(
                          'Shift starts in ${_getMinutesUntilShift()} min',
                          style: const TextStyle(
                            fontSize: 11,
                            color: Color(0xFF64748B), // slate-500
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                const Text(
                  'Track arrival',
                  style: TextStyle(
                    fontSize: 10,
                    color: Color(0xFF64748B), // slate-500
                  ),
                ),
              ],
            ),
          ),
          Switch(
            value: _localIsCommuteOn,
            onChanged: (value) {
              setState(() => _localIsCommuteOn = value);
              widget.onCommuteToggled?.call(value);
            },
            activeColor: AppColors.krowBlue,
          ),
        ],
      ),
    );
  }

  Widget _buildActiveCommuteScreen() {
    return Container(
      height: MediaQuery.of(context).size.height,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF2563EB), // blue-600
            Color(0xFF0891B2), // cyan-600
          ],
        ),
      ),
      child: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TweenAnimationBuilder(
                        tween: Tween<double>(begin: 1.0, end: 1.1),
                        duration: const Duration(seconds: 1),
                        curve: Curves.easeInOut,
                        builder: (context, double scale, child) {
                          return Transform.scale(
                            scale: scale,
                            child: Container(
                              width: 96,
                              height: 96,
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.2),
                                shape: BoxShape.circle,
                              ),
                              child: const Icon(
                                LucideIcons.navigation,
                                size: 48,
                                color: Colors.white,
                              ),
                            ),
                          );
                        },
                        onEnd: () {
                          // Restart animation
                          setState(() {});
                        },
                      ),
                      const SizedBox(height: 24),
                      const Text(
                        'On My Way',
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        'Your manager can see you\'re heading to the site',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.blue.shade100,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 32),
                      if (widget.distanceMeters != null) ...[
                        Container(
                          width: double.infinity,
                          constraints: const BoxConstraints(maxWidth: 300),
                          padding: const EdgeInsets.all(20),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          child: Column(
                            children: [
                              Text(
                                'Distance to Site',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.blue.shade100,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                _formatDistance(widget.distanceMeters!),
                                style: const TextStyle(
                                  fontSize: 36,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                        ),
                        if (widget.etaMinutes != null) ...[
                          const SizedBox(height: 12),
                          Container(
                            width: double.infinity,
                            constraints: const BoxConstraints(maxWidth: 300),
                            padding: const EdgeInsets.all(20),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(16),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.2),
                              ),
                            ),
                            child: Column(
                              children: [
                                Text(
                                  'Estimated Arrival',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.blue.shade100,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '${widget.etaMinutes} min',
                                  style: const TextStyle(
                                    fontSize: 24,
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ],
                      const SizedBox(height: 32),
                      Text(
                        'Most app features are locked while commute mode is on. You\'ll be able to clock in once you arrive.',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.blue.shade100,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(20),
              child: OutlinedButton(
                onPressed: () {
                  setState(() => _localIsCommuteOn = false);
                },
                style: OutlinedButton.styleFrom(
                  foregroundColor: Colors.white,
                  side: BorderSide(color: Colors.white.withOpacity(0.3)),
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  minimumSize: const Size(double.infinity, 48),
                ),
                child: const Text('Turn Off Commute Mode'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildArrivedCard() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFFECFDF5), // emerald-50
            Color(0xFFD1FAE5), // green-50
          ],
        ),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: const BoxDecoration(
              color: Color(0xFF10B981), // emerald-500
              shape: BoxShape.circle,
            ),
            child: const Icon(
              LucideIcons.checkCircle,
              size: 32,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 16),
          const Text(
            'You\'ve Arrived! 🎉',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Color(0xFF0F172A), // slate-900
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            'You\'re at the shift location. Ready to clock in?',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFF475569), // slate-600
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
