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 = '';

  @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');
      return;
    }

    final now = DateTime.now();
    final difference = now.difference(user!.lastPadChangeTime!);
    
    // We want to show time SINCE change (duration worn)
    final hours = difference.inHours;
    final minutes = difference.inMinutes.remainder(60);
    final seconds = difference.inSeconds.remainder(60);

    String text = '';
    
    if (user.showPadTimerMinutes) {
       if (hours > 0) text += '$hours hr ';
       text += '$minutes min';
    }
    
    if (user.showPadTimerSeconds) {
      if (text.isNotEmpty) text += ' ';
      text += '$seconds sec';
    }

    if (text.isEmpty) text = 'Active'; // Fallback

    if (mounted) {
      setState(() {
        _timeDisplay = text;
      });
    }
  }

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

    // Re-check time on rebuilds in case settings changed
    // _updateTime(); // Actually let the timer handle it, or use a key to rebuild on setting changes

    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => const PadTrackerScreen()),
        ).then((_) => _updateTime());
      },
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppColors.menstrualPhase.withOpacity(0.1),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.menstrualPhase.withOpacity(0.3)),
          boxShadow: [
             BoxShadow(
              color: AppColors.menstrualPhase.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: AppColors.menstrualPhase.withOpacity(0.2),
                shape: BoxShape.circle,
              ),
              child: const Icon(Icons.timer_outlined, color: AppColors.menstrualPhase, size: 24),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Pad Tracker',
                    style: GoogleFonts.outfit(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: AppColors.charcoal,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _timeDisplay.isNotEmpty ? _timeDisplay : 'Tap to track',
                    style: GoogleFonts.outfit(
                      fontSize: 14, 
                      fontWeight: FontWeight.w500,
                      color: AppColors.menstrualPhase
                    ),
                  ),
                ],
              ),
            ),
            const Icon(Icons.chevron_right, color: AppColors.menstrualPhase),
          ],
        ),
      ),
    );
  }
}
