import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/helpers/services/api_service.dart';
import 'package:marco/model/project_model.dart';
import 'package:marco/model/dailyTaskPlanning/daily_task_model.dart';

class DailyTaskController extends GetxController {
  List<ProjectModel> projects = [];
  String? selectedProjectId;

  DateTime? startDateTask;
  DateTime? endDateTask;

  List<TaskModel> dailyTasks = [];
  final RxSet<String> expandedDates = <String>{}.obs;

  void toggleDate(String dateKey) {
    if (expandedDates.contains(dateKey)) {
      expandedDates.remove(dateKey);
    } else {
      expandedDates.add(dateKey);
    }
  }

  RxBool isLoading = true.obs;
  Map<String, List<TaskModel>> groupedDailyTasks = {};

  @override
  void onInit() {
    super.onInit();
    _initializeDefaults();
  }

  void _initializeDefaults() {
    _setDefaultDateRange();
  }

  void _setDefaultDateRange() {
    final today = DateTime.now();
    startDateTask = today.subtract(const Duration(days: 7));
    endDateTask = today;

    logSafe(
      "Default date range set: $startDateTask to $endDateTask",
      level: LogLevel.info,
    );
  }

  Future<void> fetchTaskData(String? projectId) async {
    if (projectId == null) {
      logSafe("fetchTaskData: Skipped, projectId is null",
          level: LogLevel.warning);
      return;
    }

    isLoading.value = true;

    final response = await ApiService.getDailyTasks(
      projectId,
      dateFrom: startDateTask,
      dateTo: endDateTask,
    );

    isLoading.value = false;

    if (response != null) {
      groupedDailyTasks.clear();

      for (var taskJson in response) {
        final task = TaskModel.fromJson(taskJson);
        final assignmentDateKey =
            task.assignmentDate.toIso8601String().split('T')[0];

        groupedDailyTasks.putIfAbsent(assignmentDateKey, () => []).add(task);
      }

      dailyTasks = groupedDailyTasks.values.expand((list) => list).toList();

      logSafe(
        "Daily tasks fetched and grouped: ${dailyTasks.length} for project $projectId",
        level: LogLevel.info,
      );

      update();
    } else {
      logSafe(
        "Failed to fetch daily tasks for project $projectId",
        level: LogLevel.error,
      );
    }
  }

  Future<void> selectDateRangeForTaskData(
    BuildContext context,
    DailyTaskController controller,
  ) async {
    final picked = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2022),
      lastDate: DateTime.now(),
      initialDateRange: DateTimeRange(
        start:
            startDateTask ?? DateTime.now().subtract(const Duration(days: 7)),
        end: endDateTask ?? DateTime.now(),
      ),
    );

    if (picked == null) {
      logSafe("Date range picker cancelled by user.", level: LogLevel.debug);
      return;
    }

    startDateTask = picked.start;
    endDateTask = picked.end;

    logSafe(
      "Date range selected: $startDateTask to $endDateTask",
      level: LogLevel.info,
    );

    await controller.fetchTaskData(controller.selectedProjectId);
  }

void refreshTasksFromNotification({
  required String projectId,
  required String taskAllocationId,
}) async {
  // re-fetch tasks
  await fetchTaskData(projectId);

  update(); // rebuilds UI
}

}
