import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/InspectionsRepository.dart';
import 'package:road24_mobile/data/repository/ManualDirectusRepository.dart';
import 'package:road24_mobile/data/response/InspectionPlacesResponse.dart';
import 'package:road24_mobile/data/response/manual_part/inspection/InspectionManualResponse.dart';
import 'package:road24_mobile/data/response/manual_part/inspection/RegionsModel.dart';
import 'package:road24_mobile/view/mycar/add/inspection/inspection_page.dart';
import 'package:intl/intl.dart';
import 'package:road24_mobile/view/mycar/add/inspection/model/ispection_model.dart';
import 'package:road24_mobile/utils/extensions.dart';

part 'inspections_event.dart';

part 'inspections_state.dart';

class InspectionsBloc extends Bloc<InspectionsEvent, InspectionsState> {
  final InspectionsRepository repository;

  InspectionsBloc({required this.repository}) : super(InspectionsInitial());

  @override
  Stream<InspectionsState> mapEventToState(
    InspectionsEvent event,
  ) async* {
    if (event is GetInspectionPlacesEvent) {
      try {
        yield InspectionsInitial();

        final dynamic response = await repository.getPlaces();

        yield GetInspectionPlacesSuccessState(
          response: InspectionPlacesResponse.fromJson(response),
        );
      } catch (e) {
        yield InspectionsLoadingError(exception: e);
      }
    } else if (event is GetRegionsEvent) {
      print("region event");
      var manualRepo = ManualDirectusRepository();
      try {
        yield LoadingState();

        final dynamic response = await manualRepo.getRegions();

        yield GetRegionSuccessState(regions: response);
      } catch (ex) {
        print("inspection region exception $ex");

        yield InspectionsLoadingError(exception: ex);
      }
    } else if (event is GetListOfPlacesEvent) {
      print("place event");

      var manualRepo = ManualDirectusRepository();

      try {
        yield LoadingState();

        final dynamic districtResponse = await manualRepo.getDistricts();

        final dynamic addressResponse =
            await manualRepo.getPlaces(event.regionId);

        yield GetPlacesSuccessState(
            address: addressResponse, district: districtResponse);
      } catch (ex) {
        print("inspection exception $ex");

        yield InspectionsLoadingError(exception: ex);
      }
    } else if (event is CheckStatus) {
      var status;
      if (event.dateStart == null && event.dateEnd == null) {
        status = StatusType.NOT_FOUND;
      } else if (event.dateStart != null &&
          event.dateEnd != null &&
          event.pDivision != null) {
        try {
          var dEnd;
          var dNow = DateTime.now().toLocal();
          if (event.dateEnd!.contains("/")) {
            var americanFormat = DateFormat('MM/dd/yy hh:mm:ss a');
            dEnd = americanFormat.parse(event.dateEnd!).toLocal();
          } else {
            dEnd = DateTime.parse(event.dateEnd!).toLocal();
          }
          if (dEnd.isBefore(dNow)) {
            status = StatusType.TIME_PASSED;
          } else if (dEnd.difference(dNow).inDays < 60) {
            status = StatusType.RUNNING_OUT;
          } else {
            status = StatusType.SUCCESS;
          }
        } catch (e) {
          print("status error inspection  $e");
          status = StatusType.ERROR_DETAILS;
        }
      } else if (event.dateStart != null ||
          event.dateEnd != null ||
          event.pDivision != null) {
        status = StatusType.ERROR_DETAILS;
      }
      yield InspectionStatus(
          statusType: status,
          dateEnd: (event.dateEnd ?? "").toFormatDate(),
          datePassed: (event.dateStart ?? "").toFormatDate(),
          pDivision: event.pDivision);
    } else if (event is RefreshedInspectionInfo) {
      yield LoadingState();
      var inspection;
      try {
        final data = await repository.check(carDetailId: event.carId);

        if (data != null) inspection = InspectionModel.fromJson(data);

        if (inspection != null && inspection.response != null) {
          var result = inspection.response!.result;
          if (inspection.response!.result.vehicle.isNotEmpty &&
              inspection.response!.result.vehicle[0].inspection != null) {
            final vehicle = inspection.response!.result.vehicle[0];

            var _datePassed = vehicle.inspection!.dateInpsection;

            var _dateEnd = vehicle.inspection!.dateNextInpsection;

            var _pDivision = vehicle.pDivision;

            add(CheckStatus(
                dateEnd: _dateEnd,
                dateStart: _datePassed,
                pDivision: _pDivision));
          } else if (result.code == 404) {
            yield InspectionStatus(statusType: StatusType.NOT_FOUND);
          }
        }
      } catch (e) {
        yield InspectionsLoadingError(exception: e);
        // ScaffoldMessenger.of(context).showSnackBar(
        //   SnackBar(
        //     content: Text('$e'),
        //     duration: const Duration(milliseconds: 3500),
        //     backgroundColor: AppColors.colorf51a51,
        //   ),
        // );
      }
      // try {
      //   carDetail = await _repo.getInspection(carDetail: carId);
      // } catch (e) {}

    }
  }
}
