import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart'; // Per kIsWeb
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/company/data/company_repository.dart';
import 'package:flux/features/company/models/company_model.dart';
import 'package:get_it/get_it.dart';

part 'company_settings_state.dart';

class CompanySettingsCubit extends Cubit<CompanySettingsState> {
  final CompanyRepository _repository = GetIt.I<CompanyRepository>();
  final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();

  CompanySettingsCubit() : super(const CompanySettingsState());

  void initSettings() {
    final currentCompany = _sessionCubit.state.company;
    if (currentCompany != null) {
      emit(
        state.copyWith(
          company: currentCompany,
          status: CompanySettingsStatus.ready,
        ),
      );
    }
  }

  void updateFields({
    String? name,
    String? vatId, // Modificato da vatNumber a vatId
    String? fiscalCode, // Aggiunto
    String? sdi, // Aggiunto
    String? address,
    String? city,
    String? province, // Aggiunto
    String? zipCode,
    String? phone,
    String? email,
    String? ticketDisclaimer,
    LabelFormat? labelFormat,
    double? labelWidth,
    double? labelHeight,
    bool? isVertical,
  }) {
    if (state.company == null) return;

    final updated = state.company!.copyWith(
      name: name ?? state.company!.name,
      vatId: vatId ?? state.company!.vatId,
      fiscalCode: fiscalCode ?? state.company!.fiscalCode,
      sdi: sdi ?? state.company!.sdi,
      address: address ?? state.company!.address,
      city: city ?? state.company!.city,
      province: province ?? state.company!.province,
      zipCode: zipCode ?? state.company!.zipCode,
      phone: phone ?? state.company!.phone,
      email: email ?? state.company!.email,
      ticketDisclaimer: ticketDisclaimer ?? state.company!.ticketDisclaimer,
      labelFormat: labelFormat ?? state.company!.labelFormat,
      labelWidth: labelWidth ?? state.company!.labelWidth,
      labelHeight: labelHeight ?? state.company!.labelHeight,
      isLabelVertical: isVertical ?? state.company!.isLabelVertical,
    );
    emit(state.copyWith(company: updated));
  }

  Future<void> saveSettings() async {
    if (state.company == null) return;
    emit(
      state.copyWith(status: CompanySettingsStatus.saving, errorMessage: null),
    );

    try {
      // 1. Salva i dati su Supabase
      final updatedCompany = await _repository.updateCompany(state.company!);

      // 2. Aggiorna la sessione globale per riflettere i cambiamenti in tutta l'app
      _sessionCubit.updateCurrentCompany(updatedCompany);

      emit(
        state.copyWith(
          status: CompanySettingsStatus.success,
          company: updatedCompany,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: CompanySettingsStatus.failure,
          errorMessage: e.toString(),
        ),
      );
    }
  }

  // Metodo per gestire l'upload del logo
  Future<void> uploadLogo(Uint8List bytes, String fileName) async {
    if (state.company == null) return;
    emit(state.copyWith(status: CompanySettingsStatus.uploadingLogo));

    try {
      // Usa il tuo repository per caricare il file nel bucket 'company_logos'
      // Il file può essere Uint8List (se sei su Web) o File (se sei su Mobile/Desktop)
      final publicUrl = await _repository.uploadCompanyLogo(
        companyId: state.company!.id!,
        fileBytes: bytes,
        fileName: fileName,
      );

      final updatedCompany = state.company!.copyWith(logoUrl: publicUrl);

      emit(
        state.copyWith(
          company: updatedCompany,
          status: CompanySettingsStatus.ready,
        ),
      );

      // Chiamiamo il salvataggio per rendere definitivo l'URL nel record della compagnia
      await saveSettings();
    } catch (e) {
      emit(
        state.copyWith(
          status: CompanySettingsStatus.failure,
          errorMessage: "Errore caricamento logo: $e",
        ),
      );
    }
  }
}
