import 'package:collection/collection.dart';
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/master_data/products/data/product_repository.dart';
import 'package:flux/features/master_data/products/models/brand_model.dart';
import 'package:flux/features/master_data/products/models/model_model.dart';
import 'package:get_it/get_it.dart';

part 'product_state.dart';

class ProductsCubit extends Cubit<ProductState> {
  final ProductRepository _repository = GetIt.I<ProductRepository>();
  final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();

  ProductsCubit() : super(const ProductState());

  // Caricamento iniziale dei Brand
  Future<void> loadBrands() async {
    emit(state.copyWith(status: ProductStatus.loading));
    try {
      final brands = await _repository.getBrands();
      emit(state.copyWith(status: ProductStatus.success, brands: brands));
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  Future<void> loadModels() async {
    emit(state.copyWith(status: ProductStatus.loading));
    try {
      final models = await _repository.getModels();
      emit(state.copyWith(status: ProductStatus.success, models: models));
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  Future<void> refreshCubit() async {
    if (state.selectedBrand != null) {
      await selectBrand(state.selectedBrand);
    } else {
      emit(state.copyWith(status: ProductStatus.initial));
      await loadBrands();
    }
  }

  // Selezione Brand e caricamento Modelli
  Future<void> selectBrand(BrandModel? brand) async {
    if (brand == null) {
      emit(state.copyWith(selectedBrand: null, models: []));
      return;
    }

    emit(state.copyWith(status: ProductStatus.loading, selectedBrand: brand));
    try {
      final models = await _repository.getModelsByBrand(brand.id!);
      emit(state.copyWith(status: ProductStatus.success, models: models));
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  // Aggiungi/Modifica Brand
  Future<void> saveBrand(String name, {String? id}) async {
    try {
      final brand = BrandModel(
        id: id,
        name: name,
        companyId: _sessionCubit.state.company!.id!,
      );
      final newBrand = await _repository.upsertBrand(brand);
      await loadBrands(); // Ricarichiamo la lista aggiornata
      selectBrand(newBrand);
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  // Aggiungi/Modifica Modello
  Future<void> saveModel(String name, {String? id}) async {
    if (state.selectedBrand == null) return;

    try {
      final model = ModelModel(
        id: id,
        name: name,
        brandId: state.selectedBrand!.id!,
        nameWithBrand: '', // Gestito dal trigger SQL
      );
      await _repository.upsertModel(model);
      await selectBrand(
        state.selectedBrand,
      ); // Ricarichiamo i modelli del brand
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  // Disattivazione (Soft Delete)
  Future<void> toggleStatus(String table, String id, bool currentStatus) async {
    try {
      await _repository.toggleActiveStatus(table, id, !currentStatus);
      if (table == 'brand') {
        await loadBrands();
      } else {
        await selectBrand(state.selectedBrand);
      }
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  Future<void> searchModels(String query) async {
    if (query.isEmpty) {
      // Se cancella tutto, potresti voler ricaricare i modelli del brand selezionato
      // o svuotare la lista. Scegliamo di svuotare per pulizia.
      emit(state.copyWith(models: []));
      return;
    }

    // Opzionale: emetti loading solo se vuoi mostrare una barretta nella UI
    // emit(state.copyWith(status: ProductStatus.loading));

    try {
      final results = await _repository.searchModels(query);
      emit(state.copyWith(status: ProductStatus.success, models: results));
    } catch (e) {
      emit(
        state.copyWith(status: ProductStatus.error, errorMessage: e.toString()),
      );
    }
  }

  Future<ModelModel?> quickCreateProduct({
    required String brandName,
    required String modelName,
  }) async {
    try {
      await loadBrands();
      BrandModel? brand = state.brands.firstWhereOrNull(
        (b) => b.name.toLowerCase() == brandName.toLowerCase(),
      );
      // 1. Cerchiamo o creiamo il Brand
      // (Usa una funzione upsert o una ricerca rapida nel repository)
      brand ??= await _repository.upsertBrand(
        BrandModel(
          name: brandName,
          companyId: _sessionCubit.state.company!.id!,
        ),
      );

      // 2. Creiamo il Modello legato al Brand
      final newModel = await _repository.upsertModel(
        ModelModel(brandId: brand.id!, name: modelName),
      );

      // 3. Aggiorniamo lo stato locale così la lista modelli lo vede subito
      emit(state.copyWith(models: [newModel, ...state.models]));

      return newModel;
    } catch (e) {
      emit(state.copyWith(errorMessage: "Errore creazione rapida: $e"));
      return null;
    }
  }
}
