import 'package:cargocalculaterapp/core/extension/build_context_extension.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../../../constants/constants.dart';
import '../../../../../generated/l10n.dart';
import '../../../../../router/app_routes.dart';
import '../../../../../router/name_routes.dart';
import '../../../data/model/lead_create_request.dart';
import '../../../domain/usecase/create_lead_usecase.dart';
import '../../arguments/calculator_info_argument.dart';
import '../../pages/calculator_info/dialog/order_dialog.dart';

part 'calculator_info_event.dart';

part 'calculator_info_state.dart';

class CalculatorInfoBloc
    extends Bloc<CalculatorInfoEvent, CalculatorInfoState> {
  CalculatorInfoBloc(this.createLeadUseCase)
    : super(const CalculatorInfoState(isLoading: false)) {
    on<CreateLeadEvent>(_createLead);
    on<ShowSuccessDialogEvent>(_showSuccessDialog);
  }

  final CreateLeadUseCase createLeadUseCase;

  Future<void> _createLead(
    CreateLeadEvent event,
    Emitter<CalculatorInfoState> emit,
  ) async {
    emit(state.copyWith(isLoading: true));
    final local = Localizations.localeOf(
      rootNavigatorKey.currentContext!,
    ).languageCode;
    final response = await createLeadUseCase(
      LeadCreateRequest(
        status: "NOT_CONTACTED",
        m3: "${event.argument.size}",
        averageWeightKg: "${event.argument.averageWeight}",
        weight: "${event.argument.weight}",
        nameRu: local == "ru" ? event.argument.productName : "",
        nameUz: local == "uz" ? event.argument.productName : "",
        nameZh: local == "zh" ? event.argument.productName : "",
        price: "${event.argument.deliveryPrice}",
        warehouseCode: int.tryParse(event.argument.weraHouse),
        wharehouseRu: AppConst.warehouseOptions[event.argument.weraHouse]?.ru,
        wharehouseUz: AppConst.warehouseOptions[event.argument.weraHouse]?.uz,
        wharehouseZh: AppConst.warehouseOptions[event.argument.weraHouse]?.zh,
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        emit(state.copyWith(isLoading: false));
        add(ShowSuccessDialogEvent(isCall: event.isCall));
      },
    );
  }

  void _showSuccessDialog(
    ShowSuccessDialogEvent event,
    Emitter<CalculatorInfoState> emit,
  ) {
    if (event.isCall) {
      showCupertinoModalPopup(
        context: rootNavigatorKey.currentContext!,
        builder: (context) => CupertinoActionSheet(
          actions: [
            CupertinoActionSheetAction(
              child: Text(
                "+998 99-110-22-22",
                style: TextStyle(color: context.color.primaryColor),
              ),
              onPressed: () async {
                final Uri url = Uri(scheme: 'tel', path: "+998991102222");
                if (await canLaunchUrl(url)) {
                  await launchUrl(url);
                }
                Navigator.pop(rootNavigatorKey.currentContext!, true);
              },
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.pop(rootNavigatorKey.currentContext!);
            },
            child: Text(
              AppLocalization.current.cancel,
              style: TextStyle(color: context.color.textColor),
            ),
          ),
        ),
      ).then((value) {
        if (value is bool) {
          Navigator.pushNamedAndRemoveUntil(
            rootNavigatorKey.currentContext!,
            Routes.main,
            (route) => false,
          );
        }
      });
    } else {
      showDialog(
        context: rootNavigatorKey.currentContext!,
        builder: (context) => OrderDialog(isCall: event.isCall),
      ).then((value) {
        Navigator.pushNamedAndRemoveUntil(
          rootNavigatorKey.currentContext!,
          Routes.main,
          (route) => false,
        );
      });
    }
  }
}
