import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import '../theme/app_theme.dart';
import '../providers/user_provider.dart';
import '../screens/log/pad_tracker_screen.dart';

import 'dart:async';

class PadTrackerCard extends ConsumerStatefulWidget {
  const PadTrackerCard({super.key});

  @override
  ConsumerState<PadTrackerCard> createState() => _PadTrackerCardState();
}

class _PadTrackerCardState extends ConsumerState<PadTrackerCard> {
  Timer? _timer;
  String _timeDisplay = '';
  double _progress = 0.0;
  Color _statusColor = AppColors.menstrualPhase;
  bool _isCountDown = true; // Toggle state

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _updateTime();
    });
    _updateTime();
  }

  void _updateTime() {
    final user = ref.read(userProfileProvider);
    if (user?.lastPadChangeTime == null) {
      if (mounted) {
        setState(() {
          _timeDisplay = 'Tap to start';
          _progress = 0;
          _statusColor = AppColors.menstrualPhase;
        });
      }
      return;
    }

    final now = DateTime.now();
    final difference = now.difference(user!.lastPadChangeTime!);

    // Estimate max duration based on flow
    // None/Precautionary: 8h, Spotting: 8h, Light: 6h, Medium: 4h, Heavy: 3h
    final flowIntensity = user.typicalFlowIntensity ?? 2; // Default to light
    Duration maxDuration;
    switch (flowIntensity) {
      case 0: // No Flow / Precautionary (health guideline: 8h max)
        maxDuration = const Duration(hours: 8);
        break;
      case 1: // Spotting
        maxDuration = const Duration(hours: 8);
        break;
      case 2: // Light
        maxDuration = const Duration(hours: 6);
        break;
      case 3: // Medium
        maxDuration = const Duration(hours: 4);
        break;
      case 4: // Heavy
        maxDuration = const Duration(hours: 3);
        break;
      case 5: // Very Heavy
        maxDuration = const Duration(hours: 2);
        break;
      default:
        maxDuration = const Duration(hours: 4);
    }

    final totalSeconds = maxDuration.inSeconds;
    final elapsedSeconds = difference.inSeconds;
    double progress = elapsedSeconds / totalSeconds;
    progress = progress.clamp(0.0, 1.0);

    // Determine Status Color
    Color newColor = AppColors.menstrualPhase;
    if (progress > 0.9) {
      newColor = Colors.red;
    } else if (progress > 0.75) {
      newColor = Colors.orange;
    } else {
      newColor = AppColors.menstrualPhase; // Greenish/Theme color
    }
    // Override if we want to visually show "fresh" vs "old"

    String text = '';

    if (_isCountDown) {
      final remaining = maxDuration - difference;
      final isOverdue = remaining.isNegative;
      final absRemaining = remaining.abs();
      final hours = absRemaining.inHours;
      final mins = absRemaining.inMinutes % 60;

      if (isOverdue) {
        text = 'Overdue by ${hours}h ${mins}m';
        newColor = Colors.red; // Force red if overdue
      } else {
        text = '${hours}h ${mins}m left';
      }
      _progress =
          isOverdue ? 1.0 : (1.0 - progress); // Depleting if not overdue
    } else {
      // Count Up
      final hours = difference.inHours;
      final minutes = difference.inMinutes % 60;
      text = '${hours}h ${minutes}m worn';
      _progress = progress; // Filling
    }

    if (mounted) {
      setState(() {
        _timeDisplay = text;
        _progress = _isCountDown && text.contains('Overdue') ? 1.0 : _progress;
        _statusColor = newColor;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userProfileProvider);
    if (user == null || !user.isPadTrackingEnabled) {
      return const SizedBox.shrink();
    }

    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const PadTrackerScreen()),
        ).then((_) => _updateTime());
      },
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: _statusColor.withValues(alpha: 0.3)),
          boxShadow: [
            BoxShadow(
              color: _statusColor.withValues(alpha: 0.1),
              blurRadius: 10,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: _statusColor.withValues(alpha: 0.1),
                    shape: BoxShape.circle,
                  ),
                  child:
                      Icon(Icons.timer_outlined, color: _statusColor, size: 24),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'Pad Tracker',
                            style: GoogleFonts.outfit(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: AppColors.charcoal,
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              setState(() {
                                _isCountDown = !_isCountDown;
                                _updateTime();
                              });
                            },
                            child: Icon(
                                _isCountDown
                                    ? Icons.arrow_downward
                                    : Icons.arrow_upward,
                                size: 16,
                                color: AppColors.warmGray),
                          )
                        ],
                      ),
                      const SizedBox(height: 4),
                      Text(
                        _timeDisplay.isNotEmpty ? _timeDisplay : 'Tap to track',
                        style: GoogleFonts.outfit(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                            color: _statusColor),
                      ),
                    ],
                  ),
                ),
                const Icon(Icons.chevron_right, color: AppColors.lightGray),
              ],
            ),
            const SizedBox(height: 12),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: LinearProgressIndicator(
                value: _progress,
                backgroundColor: _statusColor.withValues(alpha: 0.1),
                valueColor: AlwaysStoppedAnimation<Color>(_statusColor),
                minHeight: 6,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
