import 'dart:async';
import 'dart:typed_data';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_size_getter/image_size_getter.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/data/response/manual_part/fines/FinesManualResponse.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:road24_mobile/data/default_image.dart';
import 'package:road24_mobile/data/http/ApiException.dart';
import 'package:road24_mobile/data/repository/CarsRepository.dart';
import 'package:road24_mobile/data/repository/FinesRepository.dart';
import 'package:road24_mobile/data/response/FinesResponse.dart';
import 'package:road24_mobile/model/blocs/card/card_bloc.dart';
import 'package:road24_mobile/model/blocs/fines/fines_bloc.dart';
import 'package:road24_mobile/model/blocs/mycar/cars_bloc.dart';
import 'package:road24_mobile/model/mixins/FinesManualMixin.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/video_items.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/manual/parts/fines/details/article_detail.dart';
import 'package:road24_mobile/view/manual/parts/fines/fines_manual.dart';
import 'package:road24_mobile/view/mycar/add/inspection/widgets/custom_bottom_sheet.dart';
import 'package:road24_mobile/view/mycar/fines/payment_history.dart';
import 'package:road24_mobile/view/mycar/fines/payment/pay_form.dart';
import 'package:road24_mobile/view/settings/card/cards_page.dart';
import 'package:road24_mobile/view/settings/card/add/add_card_page.dart';
import 'package:road24_mobile/view/shimmer/fine_details_shimmer.dart';
import 'package:road24_mobile/view/widgets/bar_code_full_screen.dart';
import 'package:road24_mobile/view/widgets/custom_loading_indicator.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:road24_mobile/view/widgets/items/card_bottom_sheet_item.dart';
import 'package:road24_mobile/view/widgets/items/car_number.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:sizer/sizer.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:video_player/video_player.dart';
import 'fine_must_page.dart';
import 'fine_details_empty.dart';

class FineDetailsPage extends StatefulWidget {
  final int id;
  final bool needOpenBottomModalSheet;

  const FineDetailsPage({
    required this.id,
    this.needOpenBottomModalSheet = false,
  });

  static int? currentFineId;

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

class _FineDetailsPageState extends State<FineDetailsPage>
    with FinesManualMixin, TickerProviderStateMixin {
  final _bloc = FinesBloc(repository: FinesRepository());
  final _carBloc = CarsBloc(repository: CarsRepository());
  final scrollController = ScrollController();

  int _activeTab = 0;
  TabController? _tabController;
  bool loading = false;
  bool opened = false;
  Parts? part;
  FineDetails? fineDetails;

  Articles? article;
  String textToShow = "";

  Map<String, String> unicodeMap = {
    '0': '\u2070',
    '1': '\u00B9',
    '2': '\u00B2',
    '3': '\u00B3',
    '4': '\u2074',
    '5': '\u2075',
    '6': '\u2076',
    '7': '\u2077',
    '8': '\u2078',
    '9': '\u2079',
  };

  @override
  void initState() {
    super.initState();

    onRefresh();
  }

  @override
  void dispose() {
    _bloc.close();
    _carBloc.close();
    scrollController.dispose();
    _tabController?.dispose();
    super.dispose();
  }

  Future<void> onRefresh() async {
    _bloc.add(GetFineDetails(widget.id));
  }

  void showCards() {
    CardsPage.cardBloc.add(GetCardsEvent());
    try {
      showBarModalBottomSheet(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (context) {
            if (fineDetails != null) {
              return CardBottomSheetItem(
                dateTimeToShow: (Config.language == "oz")
                    ? DateFormat('dd-MMM yyyy, HH:mm', 'uz')
                        .format(DateTime.parse(fineDetails!.pDate).toLocal())
                        .toString()
                    : DateFormat('dd-MMM yyyy, HH:mm', Config.language)
                        .format(DateTime.parse(fineDetails!.pDate).toLocal())
                        .toString(),
                fineNumberToShow: fineDetails!.pSeryNumber,
                onAddCard: () {
                  FineDetailsPage.currentFineId = widget.id;
                  Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (context) => AddCardPage(),
                    ),
                  );
                },
                onPay: () async {
                  FineDetailsPage.currentFineId = widget.id;
                  await Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (context) => PayForm(
                        cardId:
                            CardsPage.cards[CardBottomSheetItem.currentCard].id,
                        remain: fineDetails!.remain,
                        fineToShow: fineDetails!.pSeryNumber,
                      ),
                    ),
                  );
                  onRefresh();
                },
              );
            } else
              return const SizedBox();
          });
    } catch (e) {
      print(e);
    }
  }

  String humanizeCost(String sum) {
    if (sum.endsWith('.0')) {
      sum = sum + '0';
    }
    List<String> sumBuffer = sum.split('.');
    String refactoredSumFormat =
        FrequentWidgets.intComma(int.parse(sumBuffer[0])).replaceAll(',', ' ') +
            ((sumBuffer.length > 1) ? '.' : '') +
            ((sumBuffer.length > 1) ? sumBuffer[1].toString() : '');
    refactoredSumFormat = refactoredSumFormat.replaceAll(".00", "");
    return refactoredSumFormat;
  }

  List<dynamic> parts = [];
  int count = 0;
  getViolationArticleFromParts(Parts? part) async {
    List articles = [];
    articles.addAll(FinesManual.articles);
    print(FinesManual.articles);
    print("empty?");
    print(FinesManual.articles.isEmpty);
    if (FinesManual.articles.isEmpty) {
      // print("articles are empty");
      _bloc.add(GetCategories());
      await Future.delayed(Duration(seconds: 1));
      // count++;
      // return getViolationArticleFromParts(part);
    }
    print("empty 2 ?");
    print(FinesManual.articles.isEmpty);

    articles.addAll(FinesManual.articles);
    if (part != null) {
      return articles.firstWhere((element) => element.number == part.article,
          orElse: () => null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          return (hasInternet)
              ? BlocListener(
                  bloc: _bloc,
                  listener: (context, state) async {
                    if (state is FineDetailSuccessState) {
                      fineDetails = state.response;

                      if (state.response.pViolation!.article
                              .split('X')
                              .length ==
                          2) {
                        state.response.pViolation!.article
                            .split('X')[1]
                            .runes
                            .forEach((element) {
                          textToShow =
                              state.response.pViolation!.article.split('X')[0];
                          textToShow = textToShow +
                              unicodeMap[String.fromCharCode(element)]!;
                        });
                      } else {
                        textToShow = state.response.pViolation!.article;
                      }
                      _bloc.add(GetArticleParts(
                          article: state.response.pViolation!.article
                              .replaceAll("X", "^")));

                      _carBloc.add(GetCarDetails(state.response.car!.id));

                      if (widget.needOpenBottomModalSheet && !opened) {
                        print('need bottom sheet case');
                        SchedulerBinding.instance?.addPostFrameCallback((_) {
                          scrollController.jumpTo(
                              scrollController.position.maxScrollExtent);
                        });
                        showCards();
                        opened = true;
                      }
                    } else if (state is ArticlePartsSuccessState) {
                      // parts.addAll(state.articleParts);
                      if (state.articleParts.isNotEmpty)
                        article = await getViolationArticleFromParts(
                            state.articleParts.first);
                    }
                  },
                  child: BlocBuilder(
                    bloc: _bloc,
                    builder: (context, state) {
                      if (state is FinesInitial) {
                        return const FineDetailsShimmer();
                      } else if (state is FinesFail) {
                        return FineDetailsEmpty();
                      } else if (state is GetFinesManualFail) {
                        String? text;
                        try {
                          text = state.exception.toString().getErrorText();
                        } catch (ex) {
                          text = state.exception.toString() + "";
                        }
                        Config.showSnackBar(context, text, isRed: true);
                      }
                      // if (state is FineDetailSuccessState) {
                      //   print("state is finedetails");
                      //   fineDetails = state.response;
                      // }
                      if (fineDetails != null)
                        return ModalProgressHUD(
                          inAsyncCall: loading,
                          color: AppColors.unSelectedColor,
                          progressIndicator: CircularProgressIndicator(
                            strokeWidth: 3.0,
                            valueColor: AlwaysStoppedAnimation<Color>(
                              AppColors.unSelectedColor,
                            ),
                          ),
                          dismissible: false,
                          child: Scaffold(
                              backgroundColor: AppColors.appPrimaryColor,
                              appBar: AppBar(
                                toolbarHeight: 60.0,
                                leading:
                                    FrequentWidgets.appBarBackButton(context),
                                title: Text(
                                  fineDetails!.pSeryNumber,
                                  style: AppStyle.textStyle().copyWith(
                                      color: Color(0xff282828),
                                      fontWeight: FontWeight.w600,
                                      fontSize: 20.0),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              body: RefreshIndicator(
                                color: Colors.grey,
                                onRefresh: onRefresh,
                                child: ListView(
                                  shrinkWrap: true,
                                  controller: scrollController,
                                  padding: EdgeInsets.symmetric(vertical: 6.0),
                                  children: [
                                    statusWidget(fineDetails!.pStatus),
                                    SizedBox(height: 10.0),
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 15.0),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          if (fineDetails!.plateNumber !=
                                                  null ||
                                              fineDetails!.plateNumberAndCar !=
                                                  null ||
                                              fineDetails!.pSeryNumber
                                                  .startsWith("RR"))
                                            Padding(
                                              padding: EdgeInsets.symmetric(
                                                  vertical: 12.0),
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  if (fineDetails!.pSeryNumber
                                                      .startsWith("RR"))
                                                    videoPlayerWidget(
                                                        fineDetails!),
                                                  Row(
                                                    children: [
                                                      if (fineDetails!
                                                                  .plateNumber !=
                                                              null ||
                                                          fineDetails!
                                                              .pSeryNumber
                                                              .startsWith("RR"))
                                                        imageWidget(
                                                            0, fineDetails!),
                                                      SizedBox(width: 7.0),
                                                      if (fineDetails!
                                                                  .plateNumberAndCar !=
                                                              null ||
                                                          fineDetails!
                                                              .pSeryNumber
                                                              .startsWith("RR"))
                                                        imageWidget(
                                                            1, fineDetails!),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                          SizedBox(height: 5.0),
                                          textWidget(S
                                              .of(context)
                                              .decree_number
                                              .toUpperCase()),
                                          SizedBox(height: 5.0),
                                          Center(
                                            child: GestureDetector(
                                              onTap: () {
                                                Navigator.push(
                                                  context,
                                                  CupertinoPageRoute(
                                                    builder: (context) =>
                                                        BarCodeFullScreen(
                                                      barcode: fineDetails!
                                                          .pSeryNumber,
                                                    ),
                                                  ),
                                                );
                                              },
                                              child: Container(
                                                alignment: Alignment.centerLeft,
                                                height: 80.0,
                                                child: BarcodeWidget(
                                                  barcode: Barcode.code128(),
                                                  data:
                                                      fineDetails!.pSeryNumber,
                                                  width: 60.w,
                                                  drawText: false,
                                                ),
                                              ),
                                            ),
                                          ),
                                          SizedBox(height: 12.0),
                                          carDetails(),
                                          textWidget(S
                                              .of(context)
                                              .state_of_violation
                                              .toUpperCase()),
                                          textWidget(
                                              "$textToShow${S.of(context).article}  " +
                                                  ((fineDetails!.pViolation!
                                                              .part !=
                                                          null)
                                                      ? S.of(context).part(
                                                              fineDetails!
                                                                  .pViolation!
                                                                  .part!) +
                                                          ""
                                                      : ''),
                                              fontWeight: FontWeight.w400),
                                          SizedBox(height: 20.0),
                                          textWidget(S
                                              .of(context)
                                              .description_violation
                                              .toUpperCase()),
                                          SizedBox(height: 3.0),
                                          Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.start,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              textWidget(
                                                  fineDetails!.pViolation!.desc,
                                                  fontWeight: FontWeight.w400),
                                              SizedBox(height: 1.0),
                                              moreAboutArticle(context),
                                            ],
                                          ),
                                          SizedBox(height: 20.0),
                                          textWidget(S
                                              .of(context)
                                              .place_of_violation
                                              .toUpperCase()),
                                          textWidget(fineDetails!.pPlace,
                                              fontWeight: FontWeight.w400),
                                          SizedBox(height: 20.0),
                                          if (fineDetails!.pSeryNumber
                                              .startsWith("RR"))
                                            mapWidget(fineDetails!.latitude,
                                                fineDetails!.longitude),
                                          textWidget(S
                                              .of(context)
                                              .date_of_violation
                                              .toUpperCase()),
                                          textWidget(
                                              (Config.language == "oz")
                                                  ? DateFormat(
                                                          'dd-MMM yyyy, HH:mm',
                                                          'uz')
                                                      .format(DateTime.parse(
                                                              fineDetails!
                                                                  .pDate)
                                                          .toLocal())
                                                      .toString()
                                                  : DateFormat(
                                                          'dd-MMM yyyy, HH:mm',
                                                          Config.language)
                                                      .format(DateTime.parse(
                                                              fineDetails!
                                                                  .pDate)
                                                          .toLocal())
                                                      .toString(),
                                              fontWeight: FontWeight.w400),
                                          SizedBox(height: 20.0),
                                          textWidget(
                                              "${S.of(context).sum_of_violation.toUpperCase()} (${S.of(context).without_discount.toLowerCase()})"),
                                          Text(
                                            humanizeCost(fineDetails!.pAmount),
                                            style: AppStyle.textStyle()
                                                .copyWith(
                                                    color: Color(0xffF51A51),
                                                    fontWeight: FontWeight.w600,
                                                    fontSize: 20.0),
                                            maxLines: null,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          GestureDetector(
                                            onTap: () {
                                              Navigator.push(
                                                context,
                                                CupertinoPageRoute(
                                                    builder: (_) =>
                                                        FineMustPage()),
                                              );
                                            },
                                            child: infoWidget("info.svg",
                                                S.of(context).fines_must_title),
                                          ),
                                          if (fineDetails!.pdf != null)
                                            GestureDetector(
                                              onTap: () {
                                                launch(fineDetails!.pdf!.file!);
                                              },
                                              child: infoWidget("pdf.svg",
                                                  S.of(context).download_pdf),
                                            ),
                                          // SizedBox(height: 5.0),

                                          if (fineDetails!.pays!.isNotEmpty)
                                            GestureDetector(
                                              onTap: () {
                                                Navigator.push(
                                                    context,
                                                    CupertinoPageRoute(
                                                        builder: (context) =>
                                                            PaymentHistory(
                                                              paidFines:
                                                                  fineDetails!
                                                                      .pays!,
                                                            )));
                                              },
                                              child: infoWidget(
                                                Icons.access_time_outlined,
                                                S.of(context).payment_history,
                                                isIcon: true,
                                                // color: Colors.white
                                              ),
                                            ),
                                          Container(
                                            margin: EdgeInsets.symmetric(
                                              horizontal: 4.0,
                                              vertical: 8,
                                            ),
                                            width: 90.0.w,
                                            height: 1.0,
                                            color: AppColors.colorcacaca,
                                          ),

                                          (fineDetails!.pStatus == 2 ||
                                                  fineDetails!.pStatus == 5)
                                              ? SizedBox()
                                              : Padding(
                                                  padding: EdgeInsets.symmetric(
                                                      horizontal: 16.0),
                                                  child: Row(
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .center,
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceBetween,
                                                    children: [
                                                      fundsWidget(
                                                          S
                                                              .of(context)
                                                              .paid
                                                              .toUpperCase(),
                                                          fineDetails!
                                                              .discountAndPaid!
                                                              .paid
                                                              .toString()),
                                                      fundsWidget(
                                                          S
                                                              .of(context)
                                                              .remain
                                                              .toUpperCase(),
                                                          fineDetails!.remain),
                                                      InkWell(
                                                        onTap: () {
                                                          _bloc.add(
                                                              RefreshFineRemain(
                                                                  widget.id));
                                                        },
                                                        child: Icon(
                                                          Icons.refresh,
                                                          size: 40,
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                          SizedBox(height: 10.0),
                                        ],
                                      ),
                                    ),
                                    (fineDetails!.pStatus == 1 ||
                                            fineDetails!.pStatus == 3)
                                        ? CustomBottomSheet(
                                            buttonColor: AppColors.colorf51a51,
                                            onTap: () {
                                              showCards();
                                            },
                                            title: '${S.of(context).pay}',
                                          )
                                        : SizedBox()
                                  ],
                                ),
                              )),
                        );
                      else
                        return FineDetailsEmpty();
                    },
                  ),
                )
              : NoConnectionScreen(
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      FadeRoute(page: FineDetailsPage(id: widget.id)),
                    );
                  },
                );
        });
  }

  GestureDetector moreAboutArticle(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (article != null) {
          Navigator.push(
              context,
              CupertinoPageRoute(
                  builder: (context) => ArticleDetails(
                        articleId: article!.id,
                        articleNumber: article!.number,
                        articleName: article!.title,
                        url: article!.url,
                        goToPart: fineDetails!.pViolation!.part,
                      ),
                  title: article!.title));
        } else {
          print("its null");
        }
      },
      child: Text(
        S.of(context).more_detail,
        style: TextStyle(
          fontFamily: 'SF Pro',
          fontStyle: FontStyle.normal,
          fontSize: 16,
          // height: 23 / 16,
          fontWeight: FontWeight.w400,
          color: AppColors.indicatorColor,
        ),
      ),
    );
  }

  carDetails() {
    return BlocConsumer(
      bloc: _carBloc,
      listener: (context, carState) {
        if (carState is CarsLoadingError) {
          MyApp.hasInternet.value = false;
        }
      },
      builder: (context, carState) {
        if (carState is GetCarDetailsSuccessState) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              textWidget(S.of(context).car_number.toUpperCase()),
              CarNumber(carNumber: carState.response.number),
              SizedBox(height: 20.0),
              SizedBox(
                height: 50,
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: CachedNetworkImage(
                        imageUrl:
                            "${DefaultImages.brandImage(carState.response.mark)?.file}",
                        width: 50,
                        height: 50,
                        placeholder: (context, url) {
                          return Image.asset(
                            "assets/brand/placeholder.jpeg",
                            width: 50,
                            height: 50,
                            fit: BoxFit.fill,
                          );
                        },
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            "assets/brand/placeholder.jpeg",
                            width: 50,
                            height: 50,
                            fit: BoxFit.fill,
                          );
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          textWidget(carState.response.mark),
                          SizedBox(height: 3),
                          textWidget(carState.response.name),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20.0),
            ],
          );
        } else {
          return SizedBox();
        }
      },
    );
  }

  statusWidget(int statusId) {
    if (statusId < 1 || statusId > 5) return SizedBox();

    late Color color;
    late Color textColor;
    late String text;
    switch (statusId) {
      case 1:
        color = Color(0xffF6AE21);
        textColor = Color(0xff333333);
        text = S.of(context).fine_status_1;
        break;
      case 2:
        color = AppColors.selectedColor;
        textColor = Colors.white;
        text = S.of(context).fine_status_2;
        break;
      case 3:
        color = Color(0xff536AEE);
        textColor = Color(0xffFAFAFA);
        text = S.of(context).fine_status_3;
        break;
      case 4:
        color = Colors.green;
        textColor = Color(0xffFAFAFA);
        text = S.of(context).fine_status_4;
        break;
      case 5:
        color = Colors.grey;
        textColor = Color(0xffFAFAFA);
        text = S.of(context).fine_status_5;
        break;

      default:
        color = Color(0xffF6AE21);
        textColor = Color(0xff333333);
        text = S.of(context).fine_status_1;
        break;
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 1.0.w),
      child: Text(text,
          style: AppStyle.textStyle().copyWith(
              color: textColor, fontSize: 20.0, fontWeight: FontWeight.w500)),
      color: color,
    );
  }

  fundsWidget(String title, String amount) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: AppStyle.textStyle().copyWith(
              color: Color(0xff747474),
              fontSize: 18.0,
              fontWeight: FontWeight.w600),
        ),
        Text(
          humanizeCost(amount.toString()),
          style: AppStyle.textStyle().copyWith(
              color: Color(0xff333333),
              fontSize: 21.0,
              fontWeight: FontWeight.w600),
        ),
      ],
    );
  }

  onImageTap(int initialPage, FineDetails response) async {
    setState(() {
      loading = true;
    });
    try {
      ByteBuffer bytes1 =
          (await NetworkAssetBundle(Uri.parse(response.plateNumber!.file!))
                  .load(response.plateNumber!.file!))
              .buffer;
      ByteBuffer bytes2 = (await NetworkAssetBundle(
                  Uri.parse(response.plateNumberAndCar!.file!))
              .load(response.plateNumberAndCar!.file!))
          .buffer;
      double initialForFirst = 100.0.w /
          ImageSizeGetter.getSize(MemoryInput.byteBuffer(bytes1)).width;
      double initialForSecond = 100.0.w /
          ImageSizeGetter.getSize(MemoryInput.byteBuffer(bytes2)).width;
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => Container(
            color: Colors.white,
            child: SafeArea(
              child: Stack(
                children: [
                  PhotoViewGallery(
                    loadingBuilder: (context, progress) => Center(
                      child: Container(
                        width: 20.0,
                        height: 20.0,
                        child: CircularProgressIndicator(
                          strokeWidth: 3.0,
                          valueColor:
                              AlwaysStoppedAnimation(AppColors.unSelectedColor),
                        ),
                      ),
                    ),
                    backgroundDecoration: BoxDecoration(),
                    pageController: PageController(initialPage: initialPage),
                    pageOptions: <PhotoViewGalleryPageOptions>[
                      PhotoViewGalleryPageOptions(
                        imageProvider: CachedNetworkImageProvider(
                            response.plateNumber!.file!),
                        heroAttributes:
                            const PhotoViewHeroAttributes(tag: "tag1"),
                        maxScale: initialForFirst + 0.1,
                        minScale: initialForFirst,
                        initialScale: initialForFirst,
                        basePosition: Alignment.center,
                      ),
                      PhotoViewGalleryPageOptions(
                        imageProvider: CachedNetworkImageProvider(
                            response.plateNumberAndCar!.file!),
                        heroAttributes:
                            const PhotoViewHeroAttributes(tag: "tag2"),
                        maxScale: initialForSecond + 0.1,
                        minScale: initialForSecond,
                        initialScale: initialForSecond,
                      ),
                    ],
                  ),
                  Align(
                    alignment: Alignment.topLeft,
                    child: Container(
                      height: 60.0,
                      width: 56.0,
                      child: Material(
                        type: MaterialType.transparency,
                        child: InkWell(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Container(
                            alignment: Alignment.bottomLeft,
                            margin: EdgeInsets.symmetric(
                                horizontal: 10.0, vertical: 12.0),
                            decoration: BoxDecoration(
                              color: Color(0xffDFDFDF),
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: Icon(
                                Icons.arrow_back_ios_outlined,
                                size: 20.0,
                                color: Colors.black,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    } catch (e) {
      ApiException.errorMessage.value = e;
      MyApp.hasInternet.value = false;
      print(ApiException.errorMessage.value);
    }

    setState(() {
      loading = false;
    });
  }

  imageWidget(int initialPage, FineDetails response) {
    FineFile? file;
    if (initialPage == 1)
      file = response.plateNumberAndCar;
    else if (initialPage == 0) file = response.plateNumber;
    if (file != null && file.file != null)
      return Expanded(
        child: GestureDetector(
          onTap: () async {
            await onImageTap(initialPage, response);
          },
          child: Container(
            // margin: EdgeInsets.symmetric(horizontal: 6),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(3.0),
              border: Border.all(color: AppColors.color333333, width: 1.0),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(3.0),
              child: CachedNetworkImage(
                height: 110.0,
                imageUrl: file.file!,
                fit: BoxFit.contain,
                placeholder: (context, url) {
                  return Center(
                    child: Container(
                      width: 5.0,
                      child: AspectRatio(
                        aspectRatio: 1.0,
                        child: CustomLoadingIndicator(
                          color: AppColors.unSelectedColor,
                        ),
                      ),
                    ),
                  );
                },
                errorWidget: (context, imageUrl, newValue) {
                  return Icon(
                    Icons.image,
                    size: 25.0,
                    color: AppColors.selectedColor,
                  );
                },
              ),
            ),
          ),
        ),
      );
    else
      return SizedBox();
  }

  mapWidget(double? lat, double? long) {
    if (lat != null && long != null) {
      final _kGooglePlex = LatLng(lat, long);

      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 4,
          ),
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(3.0),
              border: Border.all(color: AppColors.color333333, width: 1.0),
            ),
            height: 200,
            child: GoogleMap(
              tiltGesturesEnabled: false,
              onCameraMove: (CameraPosition cameraPosition) {
                print(cameraPosition.zoom);
              },
              zoomGesturesEnabled: true,
              markers: <Marker>{
                Marker(
                  markerId: MarkerId("marker_1"),
                  position: _kGooglePlex,
                )
              },
              initialCameraPosition: CameraPosition(
                target: _kGooglePlex,
                zoom: 14.0,
              ),
              // onMapCreated: (GoogleMapController controller) {
              //   _controller.complete(controller);
              // },
              gestureRecognizers: Set()
                ..add(Factory<EagerGestureRecognizer>(
                    () => EagerGestureRecognizer())),
            ),
          ),
          SizedBox(
            height: 8,
          ),
        ],
      );
    }
    return SizedBox();
  }

  infoWidget(svg, String title, {bool isIcon = false, Color? color}) {
    return Container(
      margin: EdgeInsets.symmetric(
        vertical: 5,
      ),
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color ?? Color(0xffdcdcdc),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        children: [
          Container(
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color != null
                  ? Color(0xffdfdfdf).withOpacity(0.5)
                  : Colors.white.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: isIcon
                ? Icon(svg)
                : SvgPicture.asset(
                    "assets/svg/$svg",
                    height: 20,
                    color: AppColors.selectedColor,
                  ),
          ),
          SizedBox(width: 12),
          Text(
            title,
            style: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
          Spacer(),
          Icon(
            Icons.chevron_right,
            color: Color(0xFF858585),
          ),
        ],
      ),
    );
  }

  textWidget(String title, {FontWeight fontWeight = FontWeight.w600}) {
    return Text(
      title,
      style: AppStyle.textStyle().copyWith(
          color: Color(0xff282828), fontWeight: fontWeight, fontSize: 15.0),
      maxLines: 3,
      overflow: TextOverflow.ellipsis,
    );
  }

  Widget videoPlayerWidget(FineDetails response) {
    if (response.videoLink != null) {
      if (response.extraVideoLink != null) {
        if (_tabController == null) {
          _tabController = TabController(length: 2, vsync: this);

          _tabController?.addListener(
              () => setState(() => _activeTab = _tabController!.index));
        }
        return DefaultTabController(
          length: 2,
          child: Column(
            children: [
              Container(
                height: 50.0,
                alignment: Alignment.center,
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 4),
                // margin: EdgeInsets.symmetric(horizontal: 16.0),
                decoration: BoxDecoration(
                  color: Color(0xff767680).withOpacity(0.12),
                  borderRadius: BorderRadius.circular(100.0),
                ),
                child: TabBar(
                  isScrollable: false,
                  controller: _tabController,
                  indicatorColor: Colors.transparent,
                  labelPadding: EdgeInsets.symmetric(horizontal: 0.0),
                  // indicator: BoxDecoration(
                  //   borderRadius: BorderRadius.circular(100),
                  //   color: Colors.white,
                  // ),
                  tabs: [
                    FrequentWidgets.createTabForMain(
                        "Video - 1", _activeTab == 0),
                    FrequentWidgets.createTabForMain(
                        "Video - 2", _activeTab == 1),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.only(top: 8),
                height: 200,
                child: TabBarView(
                    controller: _tabController,
                    physics: NeverScrollableScrollPhysics(),
                    children: [
                      VideoItems(
                        videoPlayerController: VideoPlayerController.network(
                          response.videoLink!.toString(),
                        ),
                        looping: false,
                        autoplay: false,
                      ),
                      // VideoItems(videoUrl: "${response.videoLink}"),
                      // VideoItems(videoUrl: "${response.extraVideoLink}"),
                      VideoItems(
                        videoPlayerController: VideoPlayerController.network(
                            response.extraVideoLink!.toString()),
                        looping: false,
                        autoplay: false,
                      ),
                    ]),
              ),
            ],
          ),
        );
      } else {
        // return VideoItems(videoUrl: "${response.videoLink}");
        return VideoItems(
          videoPlayerController:
              VideoPlayerController.network(response.videoLink!.toString()),
          looping: false,
          autoplay: false,
        );
      }
    }
    return SizedBox();
  }
}
