import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/entities/time_card.dart';
import '../../domain/repositories/time_card_repository.dart';

class TimeCardRepositoryImpl implements TimeCardRepository {
  final ShiftsRepositoryMock shiftsRepository;

  TimeCardRepositoryImpl({required this.shiftsRepository});

  @override
  Future<List<TimeCard>> getTimeCards(DateTime month) async {
    // We use ShiftsRepositoryMock as it contains shift details (title, client, etc).
    // In a real app, we might query 'TimeCards' directly or join Shift+Payment.
    // For now, we simulate TimeCards from Shifts.
    final List<Shift> shifts = await shiftsRepository.getMyShifts();

    // Map to TimeCard and filter by the requested month.
    return shifts
        .map((Shift shift) {
          double hours = 8.0;
          // Simple parse for mock
          try {
            // Assuming HH:mm
            final int start = int.parse(shift.startTime.split(':')[0]);
            final int end = int.parse(shift.endTime.split(':')[0]);
            hours = (end - start).abs().toDouble();
            if (hours == 0) hours = 8.0;
          } catch (_) {}

          return TimeCard(
            id: shift.id,
            shiftTitle: shift.title,
            clientName: shift.clientName,
            date: DateTime.tryParse(shift.date) ?? DateTime.now(),
            startTime: shift.startTime,
            endTime: shift.endTime,
            totalHours: hours,
            hourlyRate: shift.hourlyRate,
            totalPay: hours * shift.hourlyRate,
            status: _mapStatus(shift.status),
            location: shift.location,
          );
        })
        .where((TimeCard tc) =>
            tc.date.year == month.year && tc.date.month == month.month)
        .toList();
  }

  TimeCardStatus _mapStatus(String? shiftStatus) {
    if (shiftStatus == null) return TimeCardStatus.pending;
    // Map shift status to TimeCardStatus
    switch (shiftStatus.toLowerCase()) {
      case 'confirmed':
        return TimeCardStatus.pending;
      case 'completed':
        return TimeCardStatus.approved;
      case 'paid':
        return TimeCardStatus.paid;
      default:
        return TimeCardStatus.pending;
    }
  }
}
