import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/customers/data/customer_repository.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:get_it/get_it.dart';

part 'customer_form_state.dart';

class CustomerFormCubit extends Cubit<CustomerFormState> {
  final CustomerRepository _repository = GetIt.I<CustomerRepository>();
  final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();

  CustomerFormCubit({CustomerModel? existingCustomer, String? customerId})
    : super(
        CustomerFormState(customer: existingCustomer ?? CustomerModel.empty()),
      );

  Future<void> initForm({
    CustomerModel? existingCustomer,
    String? customerId,
  }) async {
    emit(state.copyWith(status: CustomerFormStatus.loading));

    try {
      if (existingCustomer != null) {
        emit(
          state.copyWith(
            customer: existingCustomer,
            status: CustomerFormStatus.ready,
          ),
        );
      } else if (customerId != null) {
        final customer = await _repository.getCustomerById(customerId);
        emit(
          state.copyWith(customer: customer, status: CustomerFormStatus.ready),
        );
      } else {
        // Nuovo cliente, inizializziamo con valori vuoti
        emit(
          state.copyWith(
            customer: CustomerModel.empty().copyWith(
              companyId: _sessionCubit.state.company!.id!,
            ),
            status: CustomerFormStatus.ready,
          ),
        );
      }
    } on Exception catch (e) {
      emit(
        state.copyWith(
          status: CustomerFormStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  void updateDoNotDisturb(bool value) {
    emit(
      state.copyWith(customer: state.customer.copyWith(doNotDisturb: value)),
    );
  }

  void updateFields({
    String? name,
    String? phoneNumber,
    String? email,
    String? note,
    bool? doNotDisturb,
    bool? isBusiness,
  }) {
    emit(
      state.copyWith(
        customer: state.customer.copyWith(
          name: name ?? state.customer.name,
          phoneNumber: phoneNumber ?? state.customer.phoneNumber,
          email: email ?? state.customer.email,
          note: note ?? state.customer.note,
          doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb,
          isBusiness: isBusiness ?? state.customer.isBusiness,
        ),
      ),
    );
  }

  Future<void> saveCustomer() async {
    emit(state.copyWith(status: CustomerFormStatus.saving));

    try {
      if (state.customer.id != null) {
        // Aggiorna cliente esistente
        await _repository.updateCustomer(state.customer);
      } else {
        // Crea nuovo cliente
        await _repository.insertCustomer(state.customer);
      }
      emit(state.copyWith(status: CustomerFormStatus.success));
    } on Exception catch (e) {
      emit(
        state.copyWith(
          status: CustomerFormStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  Future<CustomerModel?> quickCreateCustomer({
    required String name,
    String? phone,
    String? email,
    required bool isBusiness,
  }) async {
    final newCustomer = CustomerModel(
      name: name,
      phoneNumber: phone ?? '',
      email: email ?? '',
      companyId: _sessionCubit.state.company!.id!,
      note: '',
      isBusiness: isBusiness,
    );

    try {
      final saved = await _repository.insertCustomer(newCustomer);
      // Lo aggiungeremo in cima ai suggerimenti
      return saved;
    } catch (e) {
      return null;
    }
  }
}
