import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:krow_domain/krow_domain.dart';

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

class CommuteTracker extends StatefulWidget {

  const CommuteTracker({
    super.key,
    this.shift,
    this.onModeChange,
    this.onCommuteToggled,
    this.hasLocationConsent = false,
    this.isCommuteModeOn = false,
    this.distanceMeters,
    this.etaMinutes,
  });
  final Shift? shift;
  final Function(CommuteMode)? onModeChange;
  final ValueChanged<bool>? onCommuteToggled;
  final bool hasLocationConsent;
  final bool isCommuteModeOn;
  final double? distanceMeters;
  final int? 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 DateTime now = DateTime.now();
    DateTime shiftStart;
    try {
      // Try parsing startTime as full datetime first
      shiftStart = DateTime.parse(widget.shift!.startTime);
    } catch (_) {
      try {
        // Try parsing date as full datetime
        shiftStart = DateTime.parse(widget.shift!.date);
      } catch (_) {
        // Fall back to combining date and time
        shiftStart = DateTime.parse(
          '${widget.shift!.date} ${widget.shift!.startTime}',
        );
      }
    }
    final int hoursUntilShift = shiftStart.difference(now).inHours;
    final bool 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 double miles = meters / 1609.34;
    return miles < 0.1
        ? '${meters.round()} m'
        : '${miles.toStringAsFixed(1)} mi';
  }

  int _getMinutesUntilShift() {
    if (widget.shift == null) return 0;
    final DateTime now = DateTime.now();
    DateTime shiftStart;
    try {
      // Try parsing startTime as full datetime first
      shiftStart = DateTime.parse(widget.shift!.startTime);
    } catch (_) {
      try {
        // Try parsing date as full datetime
        shiftStart = DateTime.parse(widget.shift!.date);
      } catch (_) {
        // Fall back to combining date and time
        shiftStart = DateTime.parse(
          '${widget.shift!.date} ${widget.shift!.startTime}',
        );
      }
    }
    return shiftStart.difference(now).inMinutes;
  }

  @override
  Widget build(BuildContext context) {
    final CommuteMode mode = _getAppMode();
    final i18n = Translations.of(context).staff.clock_in.commute;

    // 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(i18n);

      case CommuteMode.preShiftCommuteAllowed:
        return _buildPreShiftCard(i18n);

      case CommuteMode.commuteModeActive:
        return _buildActiveCommuteScreen(i18n);

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

  Widget _buildConsentCard(TranslationsStaffClockInCommuteEn i18n) {
    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space5),
      padding: const EdgeInsets.all(UiConstants.space3),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: <Color>[
            UiColors.primary.withValues(alpha: 0.05),
            UiColors.primary.withValues(alpha: 0.1),
          ],
        ),
        borderRadius: UiConstants.radiusLg,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.05),
            blurRadius: 2,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 32,
                height: 32,
                decoration: const BoxDecoration(
                  color: UiColors.primary,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  UiIcons.mapPin,
                  size: 16,
                  color: UiColors.white,
                ),
              ),
              const SizedBox(width: UiConstants.space3),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      i18n.enable_title,
                      style: UiTypography.body2m.textPrimary,
                    ),
                    const SizedBox(height: UiConstants.space1),
                    Text(
                      i18n.enable_desc,
                      style: UiTypography.body4r.textSecondary,
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space3),
          Row(
            children: <Widget>[
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    setState(() => _localHasConsent = false);
                  },
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                      vertical: UiConstants.space2,
                    ),
                    side: const BorderSide(color: UiColors.border),
                  ),
                  child: Text(i18n.not_now, style: UiTypography.footnote1m),
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    setState(() => _localHasConsent = true);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: UiColors.primary,
                    padding: const EdgeInsets.symmetric(
                      vertical: UiConstants.space2,
                    ),
                  ),
                  child: Text(
                    i18n.enable,
                    style: UiTypography.footnote1m.white,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPreShiftCard(TranslationsStaffClockInCommuteEn i18n) {
    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space5),
      padding: const EdgeInsets.all(UiConstants.space3),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusLg,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.05),
            blurRadius: 2,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: 32,
            height: 32,
            decoration: const BoxDecoration(
              color: UiColors.bgSecondary,
              shape: BoxShape.circle,
            ),
            child: const Icon(
              UiIcons.navigation,
              size: 16,
              color: UiColors.textSecondary,
            ),
          ),
          const SizedBox(width: UiConstants.space2),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Text(
                      i18n.on_my_way,
                      style: UiTypography.body2m.textPrimary,
                    ),
                    const SizedBox(width: UiConstants.space2),
                    Row(
                      children: <Widget>[
                        const Icon(
                          UiIcons.clock,
                          size: 12,
                          color: UiColors.textInactive,
                        ),
                        const SizedBox(width: 2),
                        Text(
                          i18n.starts_in(min: _getMinutesUntilShift().toString()),
                          style: UiTypography.titleUppercase4m.textSecondary,
                        ),
                      ],
                    ),
                  ],
                ),
                Text(
                  i18n.track_arrival,
                  style: UiTypography.titleUppercase4m.textSecondary,
                ),
              ],
            ),
          ),
          Switch(
            value: _localIsCommuteOn,
            onChanged: (bool value) {
              setState(() => _localIsCommuteOn = value);
              widget.onCommuteToggled?.call(value);
            },
            activeThumbColor: UiColors.primary,
          ),
        ],
      ),
    );
  }

  Widget _buildActiveCommuteScreen(TranslationsStaffClockInCommuteEn i18n) {
    return Container(
      height: MediaQuery.of(context).size.height,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: <Color>[
            UiColors.primary,
            UiColors.iconActive,
          ],
        ),
      ),
      child: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                 child: Padding(
                   padding: const EdgeInsets.all(UiConstants.space5),
                   child: Column(
                     mainAxisAlignment: MainAxisAlignment.center,
                     children: <Widget>[
                      TweenAnimationBuilder(
                        tween: Tween<double>(begin: 1.0, end: 1.1),
                        duration: const Duration(seconds: 1),
                        curve: Curves.easeInOut,
                        builder: (BuildContext context, double scale, Widget? child) {
                          return Transform.scale(
                            scale: scale,
                            child: Container(
                              width: 96,
                              height: 96,
                              decoration: BoxDecoration(
                                color: UiColors.white.withValues(alpha: 0.2),
                                shape: BoxShape.circle,
                              ),
                              child: const Icon(
                                UiIcons.navigation,
                                size: 48,
                                color: UiColors.white,
                              ),
                            ),
                          );
                        },
                        onEnd: () {
                          // Restart animation
                          setState(() {});
                        },
                      ),
                      const SizedBox(height: UiConstants.space6),
                      Text(
                        i18n.on_my_way,
                        style: UiTypography.displayMb.white,
                      ),
                      const SizedBox(height: UiConstants.space2),
                      Text(
                        i18n.heading_to_site,
                        style: UiTypography.body2r.copyWith(
                          color: UiColors.primaryForeground.withValues(alpha: 0.8),
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: UiConstants.space8),
                      if (widget.distanceMeters != null) ...<Widget>[
                        Container(
                          width: double.infinity,
                          constraints: const BoxConstraints(maxWidth: 300),
                          padding: const EdgeInsets.all(UiConstants.space5),
                          decoration: BoxDecoration(
                            color: UiColors.white.withValues(alpha: 0.1),
                            borderRadius: UiConstants.radiusLg,
                            border: Border.all(
                              color: UiColors.white.withValues(alpha: 0.2),
                            ),
                          ),
                          child: Column(
                            children: <Widget>[
                              Text(
                                i18n.distance_to_site,
                                style: UiTypography.body2r.copyWith(
                                  color: UiColors.primaryForeground.withValues(alpha: 0.8),
                                ),
                              ),
                              const SizedBox(height: UiConstants.space1),
                              Text(
                                _formatDistance(widget.distanceMeters!),
                                style: UiTypography.displayM.white,
                              ),
                            ],
                          ),
                        ),
                        if (widget.etaMinutes != null) ...<Widget>[
                          const SizedBox(height: UiConstants.space3),
                          Container(
                            width: double.infinity,
                            constraints: const BoxConstraints(maxWidth: 300),
                            padding: const EdgeInsets.all(UiConstants.space5),
                            decoration: BoxDecoration(
                              color: UiColors.white.withValues(alpha: 0.1),
                              borderRadius: UiConstants.radiusLg,
                              border: Border.all(
                                color: UiColors.white.withValues(alpha: 0.2),
                              ),
                            ),
                            child: Column(
                              children: <Widget>[
                                Text(
                                  i18n.estimated_arrival,
                                  style: UiTypography.body2r.copyWith(
                                    color: UiColors.primaryForeground.withValues(alpha: 0.8),
                                  ),
                                ),
                                const SizedBox(height: UiConstants.space1),
                                Text(
                                  i18n.eta_label(min: widget.etaMinutes.toString()),
                                  style: UiTypography.headline1m.white,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ],
                      const SizedBox(height: UiConstants.space8),
                      Text(
                        i18n.locked_desc,
                        style: UiTypography.footnote1r.copyWith(
                          color: UiColors.primaryForeground.withValues(alpha: 0.8),
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(UiConstants.space5),
              child: OutlinedButton(
                onPressed: () {
                  setState(() => _localIsCommuteOn = false);
                },
                style: OutlinedButton.styleFrom(
                  foregroundColor: UiColors.white,
                  side: BorderSide(color: UiColors.white.withValues(alpha: 0.3)),
                  padding: const EdgeInsets.symmetric(
                    vertical: UiConstants.space4,
                  ),
                  minimumSize: const Size(double.infinity, 48),
                ),
                child: Text(i18n.turn_off, style: UiTypography.buttonL),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildArrivedCard(TranslationsStaffClockInCommuteEn i18n) {
    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space5),
      padding: const EdgeInsets.all(UiConstants.space5),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: <Color>[
            UiColors.tagSuccess,
            UiColors.tagActive,
          ],
        ),
        borderRadius: UiConstants.radiusLg,
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: <Widget>[
          Container(
            width: 64,
            height: 64,
            decoration: const BoxDecoration(
              color: UiColors.success,
              shape: BoxShape.circle,
            ),
            child: const Icon(
              UiIcons.check,
              size: 32,
              color: UiColors.white,
            ),
          ),
          const SizedBox(height: UiConstants.space4),
          Text(
            i18n.arrived_title,
            style: UiTypography.headline3m.textPrimary,
          ),
          const SizedBox(height: UiConstants.space2),
          Text(
            i18n.arrived_desc,
            style: UiTypography.body2r.textSecondary,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
