import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/data/repository/InspectionsRepository.dart';
import 'package:road24_mobile/model/blocs/inspections/inspections_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/manual/parts/inspection/inspection_manual.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'inspection_must_know.dart';
import 'widgets/widgets.dart';

enum StatusType { NOT_FOUND, ERROR_DETAILS, RUNNING_OUT, TIME_PASSED, SUCCESS }

class InspectionPage extends StatefulWidget {
  final int? id;
  final int carId;
  final String? datePassed;
  final String? dateEnd;
  final String? pDivision;

  const InspectionPage({
    this.id,
    required this.carId,
    this.datePassed,
    this.dateEnd,
    this.pDivision,
  });

  @override
  _InspectionPageState createState() => _InspectionPageState();
}

class _InspectionPageState extends State<InspectionPage> {
  var _bloc = InspectionsBloc(repository: InspectionsRepository());
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();

    _bloc.add(CheckStatus(
        dateEnd: widget.dateEnd,
        dateStart: widget.datePassed,
        pDivision: widget.pDivision));
  }

  @override
  void dispose() {
    _bloc.close();

    super.dispose();
  }

  void onMustKnowPressed(BuildContext context) {
    Navigator.push(
      context,
      CupertinoPageRoute(builder: (_) => InspectionMustKnow()),
    );
  }

  void onTechDepartmentPressed(BuildContext context) {
    Navigator.push(
      context,
      CupertinoPageRoute(builder: (_) => InspectionManual()),
    );
  }

  String? _datePassed;
  String? _dateEnd;
  StatusType? status;

  String? _pDivision;
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool value, child) => value
            ? BlocBuilder(
                bloc: _bloc,
                builder: (context, state) {
                  if (state is InspectionStatus) {
                    status = state.statusType;
                    _dateEnd = state.dateEnd;
                    _datePassed = state.datePassed;
                    if (_dateEnd != null) {
                      _dateEnd = _dateEnd!.toUpperCase();
                    }
                    if (_datePassed != null) {
                      _datePassed = _datePassed!.toUpperCase();
                    }
                    _pDivision = state.pDivision;
                  } else if (state is InspectionsLoadingError) {
                    String text = "";
                    try {
                      text = state.exception.toString().getErrorText();
                    } catch (ex) {
                      text = state.exception.toString();
                    }
                    Config.showSnackBar(context, '$text');
                  }
                  return ModalProgressHUD(
                    inAsyncCall: state is LoadingState,
                    progressIndicator: CircularProgressIndicator(
                      strokeWidth: 3.0,
                      valueColor:
                          AlwaysStoppedAnimation(AppColors.unSelectedColor),
                    ),
                    child: Scaffold(
                      key: scaffoldKey,
                      backgroundColor: AppColors.appPrimaryColor,
                      appBar: CustomAppBar(
                        titleText: S.of(context).technical_inspection,
                      ),
                      bottomSheet: CustomBottomSheet(
                        onTap: () => Navigator.pop(context),
                        buttonColor: Colors.black,
                        title: '${S.of(context).back}',
                      ),
                      body: SingleChildScrollView(
                        physics: const BouncingScrollPhysics(),
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            children: [
                              _widgetWarningCard(context, status),
                              CustomNextButton(
                                icon: SvgPicture.asset('assets/svg/info.svg'),
                                text: S.of(context).my_car_important_to_know,
                                margin: EdgeInsets.only(bottom: 12),
                                onTap: () => onMustKnowPressed(context),
                              ),
                              CustomNextButton(
                                icon:
                                    SvgPicture.asset('assets/svg/location.svg'),
                                text: S.of(context).technical_department,
                                margin: EdgeInsets.only(bottom: 12),
                                onTap: () => onTechDepartmentPressed(context),
                              ),
                              // CustomInfoText(
                              //   margin: EdgeInsets.only(bottom: 28),
                              //   text: S.of(context).technical_info,
                              // ),
                              (status == StatusType.NOT_FOUND)
                                  ? notFoundWidget()
                                  : _widgetInfo(context),
                              SizedBox(height: 120),
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                })
            : NoConnectionScreen(
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    FadeRoute(
                      page: InspectionPage(
                        id: widget.id,
                        carId: widget.carId,
                        datePassed: widget.datePassed,
                        dateEnd: widget.dateEnd,
                        pDivision: widget.pDivision,
                      ),
                    ),
                  );
                },
              ));
  }

  Widget _widgetWarningCard(BuildContext context, StatusType? statusType) {
    if (statusType == StatusType.SUCCESS || statusType == StatusType.NOT_FOUND)
      return SizedBox();

    if (statusType == StatusType.RUNNING_OUT)
      return CustomWarningCard(
        title: S.of(context).technical_warning,
        content: S.of(context).technical_warning_running_out,
        margin: EdgeInsets.only(bottom: 24),
      );

    if (statusType == StatusType.TIME_PASSED)
      return CustomWarningCard(
        title: S.of(context).technical_warning,
        content: S.of(context).technical_warning_time_passed,
        margin: EdgeInsets.only(bottom: 24),
      );

    if (statusType == StatusType.ERROR_DETAILS)
      return CustomWarningCard(
        title: S.of(context).technical_warning,
        content: S.of(context).technical_warning_error,
        margin: EdgeInsets.only(bottom: 24),
      );

    return SizedBox();
  }

  notFoundWidget() {
    return Column(
      children: [
        CustomInfoText(
          margin: const EdgeInsets.only(top: 16),
          text: S.of(context).technical_info,
        ),
        const SizedBox(height: 10),
        Text(
          "😔",
          style: AppStyle.textStyle().copyWith(
            fontSize: 50,
            fontWeight: FontWeight.w700,
            color: AppColors.selectedColor,
          ),
        ),
        Text(
          S.of(context).technical_no_found,
          style: AppStyle.textStyle().copyWith(
            fontSize: 22,
            fontWeight: FontWeight.w700,
            color: AppColors.selectedColor,
          ),
        ),
        const SizedBox(height: 10),
        Text(
          S.of(context).technical_no_found_text,
          style: AppStyle.textStyle().copyWith(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: AppColors.selectedColor,
          ),
        ),
        const SizedBox(height: 20),
        CustomRefreshButton(
          text: S.of(context).check,
          onTap: () {
            _bloc.add(RefreshedInspectionInfo(carId: widget.carId));
          },
        ),
      ],
    );
  }

// enum StatusType { NOT_FOUND, ERROR_DETAILS, RUNNING_OUT, TIME_PASSED, SUCCESS }
  Widget _widgetInfo(BuildContext context) {
    return Column(
      children: [
        CustomDetailsText(
          title: S.of(context).technical_date_passed.toUpperCase(),
          content: _datePassed ?? S.of(context).technical_no_found,
          error: _datePassed == null,
        ),
        const SizedBox(height: 4),
        CustomDetailsText(
          title: S.of(context).technical_date_end.toUpperCase(),
          content: _dateEnd ?? S.of(context).technical_no_found.toUpperCase(),
          error: _dateEnd == null,
        ),
        // CustomInfoText(
        //   margin: EdgeInsets.only(top: 16),
        //   text: S.of(context).technical_info,
        // ),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 4),
          child: Divider(color: Color(0xFF000000).withOpacity(0.14)),
        ),
        CustomDetailsText(
          title: S.of(context).technical_place.toUpperCase(),
          content: "${_pDivision ?? S.of(context).technical_no_found}",
        ),
        const SizedBox(height: 20),
        CustomRefreshButton(
          text: S.of(context).refresh,
          onTap: () {
            _bloc.add(RefreshedInspectionInfo(carId: widget.carId));
          },
        ),
      ],
    );
  }
}
