import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Plant care API')),
        body: CheckList(),
      ),
    );
  }
}

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

  @override
  ConsumerState<CheckList> createState() => _CheckListState();
}

class _CheckListState extends ConsumerState<CheckList> {
  @override
  Widget build(BuildContext context) {
    final todoList = ref.watch(todoListProvider);
    final completedPercentage =
        ref.watch(completedPercentageProvider).toStringAsFixed(2);
    final averageCompletedPercentage =
        ref.watch(averageCompletedPercentageProvider).toStringAsFixed(2);

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('Completed todos: $completedPercentage%'),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
              'Average completed todos over last 7 days: $averageCompletedPercentage%'),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: todoList.length,
            itemBuilder: (context, index) {
              final todo = todoList[index];
              return ListTile(
                title: Text(todo.description),
                trailing: Checkbox(
                  value: todo.completed,
                  onChanged: (value) {
                    ref.read(todoListProvider.notifier).toggle(todo.id);
                  },
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}

final todoListProvider =
    NotifierProvider<TodoList, List<Todo>>(() => TodoList());

final completedPercentageProvider = Provider<double>((ref) {
  final todoList = ref.watch(todoListProvider);
  return _calculateCompletedPercentage(todoList);
});

final averageCompletedPercentageProvider =
    StateNotifierProvider<CumulativeNotifier, double>(
  (ref) => CumulativeNotifier(ref),
);

class Todo {
  Todo({
    required this.description,
    required this.id,
    this.completed = false,
  });

  final String id;
  final String description;
  bool completed;
}

class TodoList extends Notifier<List<Todo>> {
  @override
  List<Todo> build() {
    _scheduleDailyReset();
    return _generateDailyTodoList();
  }

  void add(String description) {
    state = [
      ...state,
      Todo(id: _uuid.v4(), description: description),
    ];
  }

  void toggle(String id) {
    state = [
      for (final todo in state)
        if (todo.id == id)
          Todo(
            id: todo.id,
            completed: !todo.completed,
            description: todo.description,
          )
        else
          todo,
    ];
  }

  void edit({required String id, required String description}) {
    state = [
      for (final todo in state)
        if (todo.id == id)
          Todo(
            id: todo.id,
            completed: todo.completed,
            description: description,
          )
        else
          todo,
    ];
  }

  void remove(Todo target) {
    state = state.where((todo) => todo.id != target.id).toList();
  }

  void _scheduleDailyReset() {
    // For testing purposes, we will use a 10-second interval instead of daily reset
    const durationUntilNextReset = Duration(seconds: 10);

    Future.delayed(durationUntilNextReset, () {
      print('Regenerating todo list and updating cumulative data...');
      ref
          .read(averageCompletedPercentageProvider.notifier)
          .addCompletedPercentage(_calculateCompletedPercentage(state));
      state = _generateDailyTodoList();
      _scheduleDailyReset(); // Reschedule for the next interval
    });
  }

  List<Todo> _generateDailyTodoList() {
    return [
      Todo(
        id: _uuid.v4(),
        description: 'Water all the plants in your garden.',
      ),
      // Add more todos as needed
    ];
  }
}

double _calculateCompletedPercentage(List<Todo> todos) {
  if (todos.isEmpty) return 0;
  final completedCount = todos.where((todo) => todo.completed).length;
  return (completedCount / todos.length) * 100;
}

class CumulativeNotifier extends StateNotifier<double> {
  CumulativeNotifier(this.ref) : super(0);

  final Ref ref;
  final List<double> _percentages = [];

  void addCompletedPercentage(double percentage) {
    _percentages.add(percentage);
    if (_percentages.length > 7) {
      _percentages.removeAt(0); // Keep only the last 7 days of data
    }
    state = _calculateAverage(_percentages);
  }

  double _calculateAverage(List<double> percentages) {
    if (percentages.isEmpty) return 0;
    final sum = percentages.reduce((a, b) => a + b);
    return sum / percentages.length;
  }

  void reset() {
    _percentages.clear();
    state = 0;
  }
}

const _uuid = Uuid();

add a +Iconbutton to appbar that runs the addfunction in TodoList