import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/intl.dart';
import '../models/drink_type.dart';

class FluxService extends ChangeNotifier {
  final Box _dataBox = Hive.box('fluxData');
  final Box _settingsBox = Hive.box('fluxSettings');

  double _intake = 0.0;
  DateTime _lastSip = DateTime.now();

  Map<CozyDrinkType, double> _breakdown = {
    CozyDrinkType.Water: 0,
    CozyDrinkType.Tea: 0,
    CozyDrinkType.Coffee: 0,
    CozyDrinkType.Juice: 0,
  };

  double _dailyGoal = 2000.0;
  bool _remindersEnabled = true;
  List<double> _weeklyLogs = [];

  FluxService() {
    _loadDailyData();
  }

  double get intake => _intake;
  double get dailyGoal => _dailyGoal;
  bool get remindersEnabled => _remindersEnabled;
  double get progress => (_intake / _dailyGoal).clamp(0.0, 1.0);
  List<double> get weeklyLogs => _weeklyLogs;
  Map<CozyDrinkType, double> get breakdown => _breakdown;

  String get encouragement {
    if (progress < 0.1) return "Good morning! Let's start with a sip.";
    if (progress < 0.4) return "You're doing great, keep flowing.";
    if (progress < 0.7) return "Almost there! Stay hydrated.";
    if (progress >= 1.0) return "Wonderful! You reached your goal.";
    return "Stay balanced.";
  }

  void _loadDailyData() {
    final todayKey = DateFormat('yyyyMMdd').format(DateTime.now());
    _intake = _dataBox.get(todayKey, defaultValue: 0.0);
    int? lastTs = _dataBox.get('last_sip_ts');
    _lastSip = lastTs != null
        ? DateTime.fromMillisecondsSinceEpoch(lastTs)
        : DateTime.now();
    _dailyGoal = _settingsBox.get('goal', defaultValue: 2000.0);
    _remindersEnabled = _settingsBox.get('reminder', defaultValue: true);

    if (_weeklyLogs.isEmpty) {
      _weeklyLogs = [1800, 2100, 1500, 2400, 1900, 2000, 0];
      _weeklyLogs[6] = _intake;
    }

    _breakdown = {
      CozyDrinkType.Water: _intake * 0.6,
      CozyDrinkType.Tea: _intake * 0.2,
      CozyDrinkType.Coffee: _intake * 0.1,
      CozyDrinkType.Juice: _intake * 0.1,
    };
    notifyListeners();
  }

  void addDrink(double amount, CozyDrinkType type) {
    _intake += amount;
    _breakdown[type] = (_breakdown[type] ?? 0) + amount;
    _lastSip = DateTime.now();
    _weeklyLogs[6] = _intake;

    final todayKey = DateFormat('yyyyMMdd').format(DateTime.now());
    _dataBox.put(todayKey, _intake);
    _dataBox.put('last_sip_ts', _lastSip.millisecondsSinceEpoch);
    notifyListeners();
  }

  void updateGoal(double newGoal) {
    _dailyGoal = newGoal;
    _settingsBox.put('goal', _dailyGoal);
    notifyListeners();
  }

  void toggleReminder(bool value) {
    _remindersEnabled = value;
    _settingsBox.put('reminder', _remindersEnabled);
    notifyListeners();
  }
}
