// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// mood_quick_selector.dart
//
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/features/mood_tracker/models/mood_entry.dart';
import 'package:nokken/src/features/mood_tracker/providers/mood_state.dart';
import 'package:nokken/src/features/mood_tracker/utils/mood_utils.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/features/mood_tracker/widgets/mood_field_chips.dart';
import 'package:nokken/src/core/utils/list_extensions.dart';

/// Stateful widget for handling quick mood selection. used in daily_tracker
class MoodQuickSelector extends ConsumerStatefulWidget {
  final DateTime selectedDate;
  final MoodEntry? existingEntry;
  final Function(MoodEntry?) onNavigateToMoodTracker;

  const MoodQuickSelector({
    super.key,
    required this.selectedDate,
    this.existingEntry,
    required this.onNavigateToMoodTracker,
  });

  @override
  ConsumerState<MoodQuickSelector> createState() => _MoodQuickSelectorState();
}

class _MoodQuickSelectorState extends ConsumerState<MoodQuickSelector>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _heightAnimation;
  bool _isExpanded = false;
  MoodEntry? _lastExistingEntry;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    _heightAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _toggleExpanded() {
    setState(() {
      _isExpanded = !_isExpanded;
      if (_isExpanded) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  // Method to explicitly collapse the selector
  void collapseSelector() {
    if (_isExpanded) {
      setState(() {
        _isExpanded = false;
        _animationController.reverse();
      });
    }
  }

  void _selectMood(MoodRating mood) {
    // Create a temporary mood entry WITH NULL ID to indicate it's not from the database
    final temporaryEntry = MoodEntry(
      id: null, // Explicitly set ID to null
      date: widget.selectedDate,
      mood: mood,
      emotions: {},
    );

    // Navigate to full mood tracker with the pre-selected mood
    widget.onNavigateToMoodTracker(temporaryEntry);
  }

  @override
  Widget build(BuildContext context) {
    // Watch mood entries to ensure component rebuilds when entries change
    final moodEntries = ref.watch(moodEntriesProvider);

    // Check if there's now an entry for this date when there wasn't before
    final currentEntry = moodEntries.firstWhereOrNull((entry) =>
        DateTime(entry.date.year, entry.date.month, entry.date.day)
            .isAtSameMomentAs(DateTime(widget.selectedDate.year,
                widget.selectedDate.month, widget.selectedDate.day)));

    // If we've transitioned from no entry to having an entry, collapse the selector
    if (_lastExistingEntry == null && currentEntry != null && _isExpanded) {
      // Close the selector when returning with a new entry
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_isExpanded) {
          _toggleExpanded();
        }
      });
    }

    // Update our reference for next comparison
    _lastExistingEntry = currentEntry;

    return Card(
      child: Column(
        children: [
          // Main mood section that can be tapped
          InkWell(
            onTap: () {
              if (widget.existingEntry != null) {
                // If there's an existing entry, go directly to the edit screen
                widget.onNavigateToMoodTracker(widget.existingEntry);
              } else {
                // Otherwise toggle the mood selector
                _toggleExpanded();
              }
            },
            child: Padding(
              padding: AppTheme.standardCardPadding,
              child: _buildMoodDisplay(),
            ),
          ),

          // Animated mood options section
          AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return ClipRect(
                child: Align(
                  heightFactor: _heightAnimation.value,
                  child: child,
                ),
              );
            },
            child: _buildMoodOptions(),
          ),
        ],
      ),
    );
  }

  Widget _buildMoodDisplay() {
    if (widget.existingEntry != null) {
      // Display existing mood
      return Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.existingEntry!.mood.emoji,
            style: TextStyle(fontSize: 32, fontFamily: AppTheme.emojiStyle),
          ),
          SharedWidgets.horizontalSpace(),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.existingEntry!.mood.displayName,
                  style: AppTextStyles.titleLarge.copyWith(
                    color: MoodUtils.getMoodColor(widget.existingEntry!.mood),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SharedWidgets.verticalSpace(),
                Wrap(
                  spacing: 8.0, // Space between chips
                  runSpacing: 4.0, // Space between lines
                  children:
                      MoodFieldChips.buildMoodFieldChips(widget.existingEntry!),
                ),
              ],
            ),
          ),
        ],
      );
    } else {
      // Prompt to track mood
      return Row(
        children: [
          Icon(
            _isExpanded ? Icons.add_reaction : Icons.add_reaction,
            size: 32,
            color: AppColors.primary,
          ),
          SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
          Text(
            _isExpanded ? 'How was your day?' : 'Tap to add mood record',
            style: AppTextStyles.bodyMedium,
          ),
        ],
      );
    }
  }

  Widget _buildMoodOptions() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16, left: 16, right: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Divider between header and options
          const Divider(),
          SharedWidgets.verticalSpace(AppTheme.spacing),

          // Row of mood options
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: MoodUtils.getAllMoodRatings().map((mood) {
              return _buildMoodOption(mood);
            }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildMoodOption(MoodRating mood) {
    return GestureDetector(
      onTap: () => _selectMood(mood),
      child: Column(
        children: [
          // Mood emoji circle
          Container(
            margin: const EdgeInsets.all(4),
            height: 40,
            width: 40,
            decoration: BoxDecoration(
              color: MoodUtils.getMoodColor(mood).withAlpha(100),
              shape: BoxShape.circle,
            ),
            child: Center(
              child: Text(
                mood.emoji,
                style: const TextStyle(
                  fontSize: 24,
                  fontFamily: AppTheme.emojiStyle,
                ),
              ),
            ),
          ),

          // Mood name
          Text(
            mood.displayName,
            style: AppTextStyles.bodySmall
                .copyWith(color: MoodUtils.getMoodColor(mood)),
          ),
        ],
      ),
    );
  }
}
