import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

/// Fetches the active schedule for a user
Future<Map<String, dynamic>?> fetchActiveSchedule(String userId) async {
  if (userId.isEmpty) {
    debugPrint('fetchActiveSchedule: userId is empty');
    return null;
  }

  try {
    // Query the schedules table for active schedules
    final response = await Supabase.instance.client
        .from('schedules')
        .select('*, crops(name)')
        .eq('user_id', userId)
        .eq('status', 'active')
        .order('created_at', ascending: false)
        .limit(1);

    if (response.isEmpty) {
      debugPrint('No active schedule found for user: $userId');
      return null;
    }

    final schedule = response[0];
    final cropName = schedule['crops']['name'] as String;
    
    // Calculate progress and days left
    final startDate = DateTime.parse(schedule['start_date']);
    final endDate = DateTime.parse(schedule['end_date']);
    final today = DateTime.now();
    
    final totalDuration = endDate.difference(startDate).inDays;
    final elapsedDuration = today.difference(startDate).inDays;
    
    double progress = elapsedDuration / totalDuration;
    progress = progress.clamp(0.0, 1.0); // Ensure progress is between 0 and 1
    
    final daysLeft = endDate.difference(today).inDays;
    
    // Get current phase
    String? currentPhase;
    try {
      final phaseResponse = await Supabase.instance.client
          .from('schedule_phases')
          .select('phase_name')
          .eq('schedule_id', schedule['id'])
          .lte('start_date', today.toIso8601String())
          .gte('end_date', today.toIso8601String())
          .limit(1);
      
      if (phaseResponse.isNotEmpty) {
        currentPhase = phaseResponse[0]['phase_name'] as String;
      }
    } catch (e) {
      debugPrint('Error fetching current phase: $e');
    }
    
    return {
      'scheduleId': schedule['id'],
      'cropName': cropName,
      'startDate': startDate,
      'endDate': endDate,
      'progress': progress,
      'daysLeft': daysLeft,
      'currentPhase': currentPhase,
      'status': schedule['status'],
    };
  } catch (e) {
    debugPrint('Error fetching active schedule: $e');
    return null;
  }
}

/// Fetches recent schedules for a user
Future<List<Map<String, dynamic>>> fetchRecentSchedules(String userId) async {
  if (userId.isEmpty) {
    debugPrint('fetchRecentSchedules: userId is empty');
    return [];
  }

  try {
    final response = await Supabase.instance.client
        .from('schedules')
        .select('*, crops(name)')
        .eq('user_id', userId)
        .order('created_at', ascending: false)
        .limit(5);

    return response.map<Map<String, dynamic>>((schedule) {
      return {
        'scheduleId': schedule['id'],
        'cropName': schedule['crops']['name'] as String,
        'status': schedule['status'],
        'date': DateTime.parse(schedule['created_at']),
      };
    }).toList();
  } catch (e) {
    debugPrint('Error fetching recent schedules: $e');
    return [];
  }
} 