import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; // Per estrarre gli store
import '../models/provider_model.dart';
import '../models/provider_role.dart';
import '../models/provider_location_model.dart';
import '../data/provider_repository.dart';
part 'provider_form_state.dart';

class ProviderFormCubit extends Cubit<ProviderFormState> {
  final ProviderRepository _repository = GetIt.I.get<ProviderRepository>();
  final _client = Supabase.instance.client; // Lo usiamo al volo per gli store

  ProviderFormCubit()
    : super(
        ProviderFormState(
          provider: ProviderModel.empty(
            companyId: GetIt.I.get<SessionCubit>().state.company!.id!,
          ),
        ),
      );

  // --- INIZIALIZZAZIONE ---
  Future<void> initForm({
    required String companyId,
    ProviderModel? existingProvider,
  }) async {
    emit(state.copyWith(status: ProviderFormStatus.loading));

    try {
      // 1. Scarichiamo tutti i negozi dell'azienda
      final storesResponse = await _client
          .from(Tables.stores)
          .select('id, name')
          .eq('company_id', companyId);

      // 2. Se stiamo modificando, carichiamo gli store collegati
      List<String> linkedStoreIds = [];
      if (existingProvider != null && existingProvider.id != null) {
        // ... (Vecchio codice di recupero)
        final links = await _client
            .from(Tables.providersInStores)
            .select('store_id')
            .eq('provider_id', existingProvider.id!);
        linkedStoreIds = (links as List)
            .map((l) => l['store_id'] as String)
            .toList();
      } else {
        // --- IL TOCCO NINJA: AUTO-SELEZIONE ---
        // Se stiamo creando un nuovo fornitore e c'è 1 solo negozio in tutto il DB, accendilo!
        if ((storesResponse as List).length == 1) {
          linkedStoreIds.add(storesResponse.first['id'] as String);
        }
      }

      emit(
        state.copyWith(
          status: ProviderFormStatus.initial,
          provider:
              existingProvider ?? ProviderModel.empty(companyId: companyId),
          availableStores: storesResponse as List<dynamic>,
          selectedStoreIds: linkedStoreIds,
          localLocations: existingProvider?.locations ?? [],
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: ProviderFormStatus.failure,
          errorMessage: 'Errore durante l\'inizializzazione: $e',
        ),
      );
    }
  }

  // --- AGGIORNAMENTO CAMPI ---
  void updateFields({
    String? name,
    String? businessName,
    String? vatNumber,
    String? fiscalCode,
    String? sdiCode,
    String? emailPec,
    String? Function()? colorHex,
  }) {
    emit(
      state.copyWith(
        provider: state.provider.copyWith(
          name: name,
          businessName: businessName,
          vatNumber: vatNumber,
          fiscalCode: fiscalCode,
          sdiCode: sdiCode,
          emailPec: emailPec,
          colorHex: colorHex,
        ),
      ),
    );
  }

  // --- GESTIONE RUOLI (CHIPS) ---
  void toggleRole(ProviderRole role) {
    final currentRoles = List<ProviderRole>.from(state.provider.roles);
    if (currentRoles.contains(role)) {
      currentRoles.remove(role);
    } else {
      currentRoles.add(role);
    }
    emit(
      state.copyWith(provider: state.provider.copyWith(roles: currentRoles)),
    );
  }

  // --- GESTIONE NEGOZI ABILITATI (CHECKBOX) ---
  void toggleStore(String storeId) {
    final currentStoreIds = List<String>.from(state.selectedStoreIds);
    if (currentStoreIds.contains(storeId)) {
      currentStoreIds.remove(storeId);
    } else {
      currentStoreIds.add(storeId);
    }
    emit(state.copyWith(selectedStoreIds: currentStoreIds));
  }

  Future<void> addLocationLocal(ProviderLocationModel location) async {
    final currentLocations = List<ProviderLocationModel>.from(
      state.localLocations,
    );
    currentLocations.add(location);
    emit(state.copyWith(localLocations: currentLocations));
  }

  void removeLocationLocal(int index) {
    final currentLocations = List<ProviderLocationModel>.from(
      state.localLocations,
    );
    if (index >= 0 && index < currentLocations.length) {
      currentLocations.removeAt(index);
      emit(state.copyWith(localLocations: currentLocations));
    }
  }

  // --- SALVATAGGIO FINALE ---
  Future<void> save() async {
    // Sicurezza di base
    if (state.provider.name.trim().isEmpty) {
      emit(
        state.copyWith(
          status: ProviderFormStatus.failure,
          errorMessage: 'Il nome è obbligatorio',
        ),
      );
      return;
    }

    emit(state.copyWith(status: ProviderFormStatus.loading));

    try {
      // Passiamo provider e storeId al repository che farà la magia
      final savedProvider = await _repository.saveProvider(
        state.provider,
        state.selectedStoreIds,
      );

      if (state.localLocations.isNotEmpty) {
        for (var loc in state.localLocations) {
          final locToSave = loc.copyWith(
            providerId: savedProvider.id!,
            companyId: savedProvider.companyId,
          );
          await _repository.saveLocation(locToSave);
        }
      }

      emit(
        state.copyWith(
          status: ProviderFormStatus.success,
          provider: savedProvider,
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(
          status: ProviderFormStatus.failure,
          errorMessage: 'Errore di salvataggio: $e',
        ),
      );
    }
  }
}
