import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_driver/main.dart';

class WorkSlot {
  int dayOfWeek; // 1=Mon ... 7=Sun
  TimeOfDay startTime;
  TimeOfDay endTime;
  bool isActive;

  WorkSlot({required this.dayOfWeek, required this.startTime, required this.endTime, this.isActive = true});

  Map<String, dynamic> toJson() => {
    'day': dayOfWeek, 'startH': startTime.hour, 'startM': startTime.minute,
    'endH': endTime.hour, 'endM': endTime.minute, 'active': isActive,
  };

  factory WorkSlot.fromJson(Map<String, dynamic> json) => WorkSlot(
    dayOfWeek: json['day'] ?? 1,
    startTime: TimeOfDay(hour: json['startH'] ?? 8, minute: json['startM'] ?? 0),
    endTime: TimeOfDay(hour: json['endH'] ?? 17, minute: json['endM'] ?? 0),
    isActive: json['active'] ?? true,
  );

  String get dayName {
    const days = ['', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return days[dayOfWeek];
  }

  String get dayNameAr {
    const days = ['', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت', 'الأحد'];
    return days[dayOfWeek];
  }

  String formatTime(TimeOfDay t) => '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}';
  String get timeRange => '${formatTime(startTime)} - ${formatTime(endTime)}';
}

class ScheduleController extends GetxController {
  List<WorkSlot> schedule = [];

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

  void _loadSchedule() {
    final saved = box.read('work_schedule');
    if (saved != null) {
      try {
        final list = jsonDecode(saved) as List;
        schedule = list.map((e) => WorkSlot.fromJson(e)).toList();
      } catch (_) {
        _initDefault();
      }
    } else {
      _initDefault();
    }
    update();
  }

  void _initDefault() {
    schedule = List.generate(7, (i) => WorkSlot(
      dayOfWeek: i + 1,
      startTime: const TimeOfDay(hour: 8, minute: 0),
      endTime: const TimeOfDay(hour: 18, minute: 0),
      isActive: i < 6, // الجمعة عطلة
    ));
  }

  void _save() {
    box.write('work_schedule', jsonEncode(schedule.map((s) => s.toJson()).toList()));
    update();
  }

  void toggleDay(int dayOfWeek) {
    final slot = schedule.firstWhere((s) => s.dayOfWeek == dayOfWeek);
    slot.isActive = !slot.isActive;
    _save();
  }

  void updateStartTime(int dayOfWeek, TimeOfDay time) {
    schedule.firstWhere((s) => s.dayOfWeek == dayOfWeek).startTime = time;
    _save();
  }

  void updateEndTime(int dayOfWeek, TimeOfDay time) {
    schedule.firstWhere((s) => s.dayOfWeek == dayOfWeek).endTime = time;
    _save();
  }

  double get totalWeeklyHours {
    double total = 0;
    for (var s in schedule) {
      if (!s.isActive) continue;
      final startMin = s.startTime.hour * 60 + s.startTime.minute;
      final endMin = s.endTime.hour * 60 + s.endTime.minute;
      total += (endMin - startMin) / 60;
    }
    return total;
  }

  int get activeDays => schedule.where((s) => s.isActive).length;
}
