import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import '../../../../data/datasources/settings_local_datasource.dart';
import '../../models/tax_model.dart';

part 'tax_settings_event.dart';
part 'tax_settings_state.dart';
part 'tax_settings_bloc.freezed.dart';

class TaxSettingsBloc extends Bloc<TaxSettingsEvent, TaxSettingsState> {
  final SettingsLocalDatasource settingsLocalDatasource;

  TaxSettingsBloc(this.settingsLocalDatasource) : super(const _Initial()) {
    on<_LoadSettings>((event, emit) async {
      emit(const _Loading());
      try {
        final tax = await settingsLocalDatasource.getTax();
        final serviceCharge = await settingsLocalDatasource.getServiceCharge();
        
        emit(_Loaded(
          taxModel: tax,
          serviceChargeValue: serviceCharge,
        ));
      } catch (e) {
        emit(_Error(e.toString()));
      }
    });

    on<_SaveTax>((event, emit) async {
      emit(const _Loading());
      try {
        await settingsLocalDatasource.saveTax(event.taxModel);
        final serviceCharge = await settingsLocalDatasource.getServiceCharge();
        
        emit(_Loaded(
          taxModel: event.taxModel,
          serviceChargeValue: serviceCharge,
        ));
      } catch (e) {
        emit(_Error(e.toString()));
      }
    });

    on<_SaveServiceCharge>((event, emit) async {
      emit(const _Loading());
      try {
        await settingsLocalDatasource.saveServiceCharge(event.serviceCharge);
        final tax = await settingsLocalDatasource.getTax();
        
        emit(_Loaded(
          taxModel: tax,
          serviceChargeValue: event.serviceCharge,
        ));
      } catch (e) {
        emit(_Error(e.toString()));
      }
    });

    on<_UpdateSettings>((event, emit) async {
      emit(const _Loading());
      try {
        // Create tax model
        final taxModel = TaxModel(
          name: 'Pajak PB1',
          type: TaxType.pajak,
          value: event.taxValue,
        );
        
        await settingsLocalDatasource.saveTax(taxModel);
        await settingsLocalDatasource.saveServiceCharge(event.serviceChargeValue);
        
        emit(_Loaded(
          taxModel: taxModel,
          serviceChargeValue: event.serviceChargeValue,
        ));
      } catch (e) {
        emit(_Error(e.toString()));
      }
    });
  }
} 