import 'package:uuid/uuid.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/features/haircuts/data/models/haircut_model.dart';
import 'package:barber_app/features/finances/data/repositories/transaction_repository.dart';

class HaircutRepository {
  final _uuid = const Uuid();
  final _transactionRepo = TransactionRepository();

  String? get _currentUserId => DatabaseService.getCurrentUserId();

  // Criar corte (cria transação automaticamente)
  Future<HaircutModel?> createHaircut({
    required String clientName,
    required String serviceType,
    required double price,
    required DateTime dateTime,
    String? notes,
    bool isPaid = true,
    String paymentMethod = 'Dinheiro',
  }) async {
    if (_currentUserId == null) return null;

    final haircutId = _uuid.v4();

    // Criar transação financeira (Adicionando método de pagamento na descrição p/ facilitar controle)
    final transaction = await _transactionRepo.createRevenueFromHaircut(
      haircutId: haircutId,
      amount: price,
      clientName: '$clientName ($paymentMethod)',
      serviceType: serviceType,
      isPaid: isPaid,
    );

    final haircut = HaircutModel(
      id: haircutId,
      userId: _currentUserId!,
      clientName: clientName.trim(),
      serviceType: serviceType,
      price: price,
      dateTime: dateTime,
      notes: notes?.trim(),
      transactionId: transaction?.id,
      paymentMethod: paymentMethod,
    );

    await DatabaseService.haircutsBoxInstance.put(haircutId, haircut);
    return haircut;
  }

  // Listar todos os cortes do usuário
  List<HaircutModel> getAllHaircuts() {
    if (_currentUserId == null) return [];
    return DatabaseService.haircutsBoxInstance.values
        .where((h) => h.userId == _currentUserId)
        .toList()
      ..sort((a, b) => b.dateTime.compareTo(a.dateTime));
  }

  // Cortes de hoje
  List<HaircutModel> getTodayHaircuts() {
    final now = DateTime.now();
    final todayStart = DateTime(now.year, now.month, now.day);
    final todayEnd = todayStart.add(const Duration(days: 1));

    return getAllHaircuts()
        .where((h) => h.dateTime.isAfter(todayStart) && h.dateTime.isBefore(todayEnd))
        .toList();
  }

  // Cortes da semana
  List<HaircutModel> getWeekHaircuts() {
    final now = DateTime.now();
    final weekStart = now.subtract(Duration(days: now.weekday - 1));
    final weekStartDay = DateTime(weekStart.year, weekStart.month, weekStart.day);

    return getAllHaircuts()
        .where((h) => h.dateTime.isAfter(weekStartDay))
        .toList();
  }

  // Cortes do mês
  List<HaircutModel> getMonthHaircuts() {
    final now = DateTime.now();
    final monthStart = DateTime(now.year, now.month, 1);

    return getAllHaircuts()
        .where((h) => h.dateTime.isAfter(monthStart))
        .toList();
  }

  // Faturamento do dia
  double getTodayRevenue() {
    return getTodayHaircuts().fold(0.0, (sum, h) => sum + h.price);
  }

  // Faturamento da semana
  double getWeekRevenue() {
    return getWeekHaircuts().fold(0.0, (sum, h) => sum + h.price);
  }

  // Faturamento do mês
  double getMonthRevenue() {
    return getMonthHaircuts().fold(0.0, (sum, h) => sum + h.price);
  }

  // Atualizar corte
  Future<HaircutModel?> updateHaircut(HaircutModel haircut) async {
    await DatabaseService.haircutsBoxInstance.put(haircut.id, haircut);
    return haircut;
  }

  // Deletar corte
  Future<void> deleteHaircut(String id) async {
    final haircut = DatabaseService.haircutsBoxInstance.get(id);
    if (haircut?.transactionId != null) {
      await _transactionRepo.deleteTransaction(haircut!.transactionId!);
    }
    await DatabaseService.haircutsBoxInstance.delete(id);
  }

  // Buscar corte por ID
  HaircutModel? getHaircutById(String id) {
    return DatabaseService.haircutsBoxInstance.get(id);
  }
}
