import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:intl/intl.dart';
import '../../domain/repositories/clock_in_repository_interface.dart';

/// Implementation of [ClockInRepositoryInterface].
///
/// Delegates shift data retrieval to [ShiftsRepositoryMock] and manages purely
/// local state for attendance (check-in/out) for the prototype phase.
class ClockInRepositoryImpl implements ClockInRepositoryInterface {
  final ShiftsRepositoryMock _shiftsMock;
  
  // Local state for the session (mocking backend state)
  bool _isCheckedIn = false;
  DateTime? _checkInTime;
  DateTime? _checkOutTime;
  String? _activeShiftId;

  ClockInRepositoryImpl({ShiftsRepositoryMock? shiftsMock}) 
      : _shiftsMock = shiftsMock ?? ShiftsRepositoryMock();

  @override
  Future<Shift?> getTodaysShift() async {
    final shifts = await _shiftsMock.getMyShifts();
    
    if (shifts.isEmpty) return null;

    final now = DateTime.now();
    final todayStr = DateFormat('yyyy-MM-dd').format(now);
    
    // Find a shift effectively for today, or mock one
    try {
      return shifts.firstWhere((s) => s.date == todayStr);
    } catch (_) {
      final original = shifts.first;
      // Mock "today's" shift based on the first available shift
      return Shift(
        id: original.id,
        title: original.title,
        clientName: original.clientName,
        logoUrl: original.logoUrl,
        hourlyRate: original.hourlyRate,
        location: original.location,
        locationAddress: original.locationAddress,
        date: todayStr,
        startTime: original.startTime, // Use original times or calculate
        endTime: original.endTime,
        createdDate: original.createdDate,
        status: 'assigned',
        latitude: original.latitude,
        longitude: original.longitude,
        description: original.description,
        managers: original.managers,
      );
    }
  }

  @override
  Future<Map<String, dynamic>> getAttendanceStatus() async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _getCurrentStatusMap();
  }

  @override
  Future<Map<String, dynamic>> clockIn({required String shiftId, String? notes}) async {
    await Future.delayed(const Duration(seconds: 1)); // Simulate network
    
    _isCheckedIn = true;
    _checkInTime = DateTime.now();
    _activeShiftId = shiftId;
    _checkOutTime = null; // Reset for new check-in? Or keep for history? 
                          // Simple mock logic: reset check-out on new check-in.

    return _getCurrentStatusMap();
  }

  @override
  Future<Map<String, dynamic>> clockOut({String? notes, int? breakTimeMinutes}) async {
    await Future.delayed(const Duration(seconds: 1)); // Simulate network
    
    _isCheckedIn = false;
    _checkOutTime = DateTime.now();
    
    return _getCurrentStatusMap();
  }

  @override
  Future<List<Map<String, dynamic>>> getActivityLog() async {
    await Future.delayed(const Duration(milliseconds: 500));
    // Mock data
    return [
      {
        'date': DateTime.now().subtract(const Duration(days: 1)),
        'start': '09:00 AM',
        'end': '05:00 PM',
        'hours': '8h',
      },
      {
        'date': DateTime.now().subtract(const Duration(days: 2)),
        'start': '09:00 AM',
        'end': '05:00 PM',
        'hours': '8h',
      },
    ];
  }

  Map<String, dynamic> _getCurrentStatusMap() {
    return {
      'isCheckedIn': _isCheckedIn,
      'checkInTime': _checkInTime,
      'checkOutTime': _checkOutTime,
      'activeShiftId': _activeShiftId,
    };
  }
}
