import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:road24_mobile/data/repository/ChequeRepository.dart';
import 'package:road24_mobile/data/response/ChequeDetailsResponse.dart';
import 'package:road24_mobile/data/response/FinesResponse.dart';
import 'package:road24_mobile/model/blocs/cheque/cheque_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/utils/widget_to_image.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/widgets/items/car_number.dart';
import 'package:road24_mobile/view/widgets/list_item.dart';
import 'package:path/path.dart';
import 'package:printing/printing.dart';
import 'package:pdf/widgets.dart' as pw;
import 'fine_details_page.dart';

class FinesChequeDetails extends StatefulWidget {
  final Results results;

  const FinesChequeDetails({Key? key, required this.results}) : super(key: key);
  @override
  _FinesChequeDetailsState createState() => _FinesChequeDetailsState();
}

class _FinesChequeDetailsState extends State<FinesChequeDetails> {
  var color = Color(0xff282828);
  GlobalKey? key1;
  GlobalKey? key2;
  bool isPdf = false;

  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

  final ChequeBloc chequeBloc = ChequeBloc(repository: ChequeRepository());
  ChequeDetailsResponse? chequeDetailsResponse;
  bool loading = true;
  @override
  void initState() {
    super.initState();
    if (widget.results.checkId != null)
      chequeBloc.add(GetChequeDetails(id: widget.results.checkId!));
  }

  @override
  void dispose() {
    chequeBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.results.checkId != null)
      return paidWithRoad(context);
    else
      return outsideServicesWidget(context);
  }

  appBarWidget(String title, context) {
    return AppBar(
      backgroundColor: Colors.transparent,
      leading: FrequentWidgets.appBarBackButton(context),
      title: Text(title,
          style: AppStyle.textStyle().copyWith(
              color: Colors.black,
              fontSize: 17.0,
              fontWeight: FontWeight.w600)),
    );
  }

  paidWithRoad(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar:
          appBarWidget(chequeDetailsResponse?.fine.pSeryNumber ?? "", context),
      body: BlocListener(
        bloc: chequeBloc,
        listener: (context, state) {
          if (state is ChequeDetailsSuccessState) {
            setState(() {
              chequeDetailsResponse = state.response;
              loading = false;
            });
          }
          if (state is ChequeErrorState) {
            setState(() {
              loading = false;
            });
            Config.showSnackBar(
              context,
              state.exception.toString(),
            );
          }
        },
        child: loading
            ? Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12.0),
                  child: Column(
                    children: [
                      WidgetToImage(builder: (key) {
                        key1 = key;
                        return Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      if (chequeDetailsResponse?.carModel !=
                                          null)
                                        CarNumber(
                                            carNumber: chequeDetailsResponse!
                                                .carModel!.number!,
                                            fontSize: 17),
                                      const SizedBox(
                                        height: 8,
                                      ),
                                      SvgPicture.asset(
                                        "assets/svg/road24_icon.svg",
                                        width: 90,
                                      ),
                                    ],
                                  ),
                                  RotationTransition(
                                    turns: AlwaysStoppedAnimation(-12 / 360),
                                    child: Container(
                                      margin:
                                          EdgeInsets.only(top: 20, right: 4),
                                      decoration: BoxDecoration(
                                        border: Border.all(
                                            color: Color(0xff0057D9), width: 3),
                                      ),
                                      padding: EdgeInsets.all(4),
                                      child: Text(
                                          widget.results.remain == "0.00"
                                              ? S.of(context).paid.toUpperCase()
                                              : S
                                                  .of(context)
                                                  .partially_paid
                                                  .toUpperCase()
                                                  .replaceAll(" ", "\n"),
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              fontSize: widget.results.remain ==
                                                      "0.00"
                                                  ? 22
                                                  : 16,
                                              letterSpacing: 2,
                                              fontWeight: FontWeight.w600,
                                              color: Color(0xff0057D9))),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 20,
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                      context,
                                      CupertinoPageRoute(
                                          builder: (_) => FineDetailsPage(
                                                id: widget.results.parentId!,
                                              )));
                                },
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(S.of(context).reason,
                                        style: const TextStyle(
                                            fontSize: 17,
                                            color: Color(0xff747474),
                                            fontWeight: FontWeight.w600)),
                                    const SizedBox(
                                      height: 8,
                                    ),
                                    Row(
                                      children: [
                                        Flexible(
                                          child: Text(
                                              chequeDetailsResponse
                                                      ?.purposeText ??
                                                  "",
                                              style: TextStyle(
                                                  fontSize: 17,
                                                  fontWeight: FontWeight.w500,
                                                  color: color)),
                                        ),
                                        const SizedBox(
                                          width: 8,
                                        ),
                                        if (!isPdf)
                                          const Icon(
                                            Icons.arrow_forward_ios,
                                            size: 16,
                                          )
                                      ],
                                    ),
                                    const SizedBox(
                                      height: 8,
                                    ),
                                    const Divider(),
                                  ],
                                ),
                              ),
                              BetweenListItem(
                                title: S.of(context).sum,
                                trailingText: chequeDetailsResponse?.amount !=
                                        null
                                    ? FrequentWidgets.intComma(
                                            double.parse(
                                                chequeDetailsResponse!.amount),
                                            decimalDigit: 1) +
                                        " сум"
                                    // ? "${FrequentWidgets.intComma(chequeDetailsResponse?.amount.toString().replaceAll(".00", "") ?? "")} сум"
                                    : "",
                              ),
                              const Divider(),
                              BetweenListItem(
                                  title: S.of(context).commission,
                                  trailingText: chequeDetailsResponse
                                              ?.commission !=
                                          null
                                      ? FrequentWidgets.intComma(
                                              double.parse(
                                                  chequeDetailsResponse!
                                                      .commission),
                                              decimalDigit: 1) +
                                          " сум"
                                      // ? "${FrequentWidgets.intComma(chequeDetailsResponse?.commission.toString() ?? "")} сум"
                                      : ""),
                              const Divider(),
                              BetweenListItem(
                                  title: S.of(context).decree_number,
                                  trailingText:
                                      chequeDetailsResponse?.fine.pSeryNumber ??
                                          ""),
                              const Divider(),
                              BetweenListItem(
                                  title: S.of(context).payment_receiver,
                                  trailingText: chequeDetailsResponse
                                          ?.payeeDetails.name ??
                                      ""),
                              const SizedBox(
                                height: 8,
                              ),
                              BetweenListItem(
                                  title: S.of(context).inn,
                                  trailingText:
                                      chequeDetailsResponse?.payeeDetails.inn ??
                                          ""),
                              const SizedBox(
                                height: 8,
                              ),
                              BetweenListItem(
                                  title: S.of(context).mfo,
                                  trailingText: chequeDetailsResponse
                                          ?.payeeDetails.branch ??
                                      ""),
                              const SizedBox(
                                height: 8,
                              ),
                              BetweenListItem(
                                  title: S.of(context).acoount,
                                  trailingText: chequeDetailsResponse
                                          ?.payeeDetails.account ??
                                      ""),
                              const SizedBox(
                                height: 4,
                              ),
                              const Divider(),
                              BetweenListItem(
                                  title: S.of(context).payment_date,
                                  trailingText: chequeDetailsResponse != null
                                      ? FrequentWidgets.dateTimeToLocal(
                                          chequeDetailsResponse!.createdDate)
                                      : ""),
                              const Divider(),
                              BetweenListItem(
                                title: S.of(context).card_number,
                                trailingText: (chequeDetailsResponse != null &&
                                        chequeDetailsResponse!
                                                .bankCardModel.number !=
                                            null)
                                    ? FrequentWidgets.cardNumberFormat(
                                        chequeDetailsResponse!
                                            .bankCardModel.number!)
                                    : "",
                                subText: chequeDetailsResponse
                                        ?.bankCardModel.fullName ??
                                    "",
                                svgPath: (chequeDetailsResponse != null &&
                                        chequeDetailsResponse!
                                                .bankCardModel.number !=
                                            null)
                                    ? chequeDetailsResponse!
                                            .bankCardModel.number!
                                            .startsWith("8600")
                                        ? "uzcard_icon"
                                        : "humo"
                                    : "",
                              ),
                              const Divider(),
                              if (chequeDetailsResponse?.carModel != null)
                                BetweenListItem(
                                    title: S.of(context).car,
                                    trailingText: chequeDetailsResponse
                                                ?.carModel !=
                                            null
                                        ? "${chequeDetailsResponse?.carModel!.mark ?? ""} ${chequeDetailsResponse?.carModel!.name ?? ""} "
                                        : ""),
                              const SizedBox(
                                height: 24,
                              ),
                            ],
                          ),
                        );
                      }),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.center,
                      //   children: [
                      // buttonWidget(context, Icons.picture_as_pdf,
                      //     S.of(context).download, () async {
                      //   if (chequeDetailsResponse?.fine.pSeryNumber != null)
                      //     await savePdf(
                      //         context,
                      //         chequeDetailsResponse!.fine.pSeryNumber!,
                      //         chequeDetailsResponse!.amount);
                      // }),
                      // const SizedBox(
                      //   width: 6,
                      // ),
                      buttonWidget(
                          context, Icons.picture_as_pdf, S.of(context).download,
                          () async {
                        if (chequeDetailsResponse?.fine.pSeryNumber != null)
                          await savePdf(
                              context,
                              chequeDetailsResponse!.fine.pSeryNumber!,
                              chequeDetailsResponse!.amount,
                              isShare: true);
                      }),
                      //   ],
                      // ),
                      const SizedBox(
                        height: 28,
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  savePdf(context, String fineNumber, String amount,
      {bool isShare = false}) async {
    try {
      var bytes;
      setState(() {
        loading = true;
      });
      final directory = await getApplicationDocumentsDirectory();

      final String path = "${directory.path}/cheque_${fineNumber}_$amount.pdf";

      final file = File('$path');

      if ((await file.exists())) {
        if (isShare) {
          await Printing.sharePdf(
              bytes: await file.readAsBytes(), filename: basename(file.path));
        } else {
          await Printing.layoutPdf(
              onLayout: (PdfPageFormat format) async =>
                  await file.readAsBytes());
        }
      } else {
        if (key1 != null) bytes = await FrequentWidgets.capture(key1);

        if (bytes != null) {
          final pdf = pw.Document();

          pdf.addPage(
            pw.Page(
              pageFormat: PdfPageFormat.a4,
              build: (pw.Context context) =>
                  pw.Center(child: pw.Image(pw.MemoryImage(bytes))),
            ),
          );

          await file.writeAsBytes(await pdf.save());

          if (isShare) {
            await Printing.sharePdf(
                bytes: await pdf.save(), filename: basename(file.path));
          } else
            await Printing.layoutPdf(
                onLayout: (PdfPageFormat format) async => pdf.save());
        }
      }
    } catch (ex) {
      print("excc $ex");
      savePdf(context, fineNumber, fineNumber, isShare: isShare);
      // Config.showSnackBar(context,S.of(context).try_again, scaffoldKey);
    }
    setState(() {
      loading = false;
    });
  }

  buttonWidget(
    context,
    IconData svgFileName,
    String title,
    Function() onTap,
  ) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 60.0,
        padding: EdgeInsets.symmetric(horizontal: 6.0, vertical: 5.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.0),
          color: Colors.black,
        ),
        child: Center(
          child: Text(title,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xffFAFAFA),
              )),
        ),
      ),
    );
  }

  outsideServicesWidget(context) {
    return Scaffold(
      appBar: appBarWidget(widget.results.pSeryNumber!, context),
      body: Stack(
        fit: StackFit.expand,
        children: [
          SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 12.0),
              child: WidgetToImage(builder: (key) {
                key1 = key;
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              CarNumber(
                                  carNumber: widget.results.carNumber ?? "",
                                  fontSize: 17),
                              const SizedBox(
                                height: 8,
                              ),
                              Text(
                                "${S.of(context).others}",
                                style: AppStyle.textStyle().copyWith(
                                  color: Color(0xffF51A51),
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.w600,
                                ),
                                textAlign: TextAlign.center,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                          RotationTransition(
                            turns: AlwaysStoppedAnimation(-12 / 360),
                            child: Container(
                              margin: EdgeInsets.only(top: 20, right: 8),
                              decoration: BoxDecoration(
                                border: Border.all(
                                    color: Color(0xff0057D9), width: 3),
                              ),
                              padding: EdgeInsets.all(4),
                              child: Text(
                                  widget.results.remain == "0.00"
                                      ? S.of(context).paid.toUpperCase()
                                      : S
                                          .of(context)
                                          .partially_paid
                                          .toUpperCase()
                                          .replaceAll(" ", "\n"),
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontSize: widget.results.remain == "0.00"
                                          ? 22
                                          : 16,
                                      letterSpacing: 2,
                                      fontWeight: FontWeight.w600,
                                      color: Color(0xff0057D9))),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                              context,
                              CupertinoPageRoute(
                                  builder: (_) => FineDetailsPage(
                                        id: widget.results.parentId!,
                                      )));
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(S.of(context).reason,
                                style: const TextStyle(
                                    fontSize: 17,
                                    color: Color(0xff747474),
                                    fontWeight: FontWeight.w600)),
                            const SizedBox(
                              height: 8,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Flexible(
                                  child: Text(
                                      widget.results.pViolation?.desc ?? "",
                                      style: TextStyle(
                                          fontSize: 17,
                                          fontWeight: FontWeight.w500,
                                          color: color)),
                                ),
                                const SizedBox(
                                  width: 8,
                                ),
                                if (!isPdf)
                                  const Icon(
                                    Icons.arrow_forward_ios,
                                    size: 16,
                                  )
                              ],
                            ),
                            const SizedBox(
                              height: 8,
                            ),
                          ],
                        ),
                      ),
                      const Divider(),
                      BetweenListItem(
                          title: S.of(context).sum,
                          trailingText: FrequentWidgets.intComma(
                                  double.parse(widget.results.pAmount!),
                                  decimalDigit: 1) +
                              "сум"),
                      const Divider(),
                      BetweenListItem(
                          title: S.of(context).decree_number,
                          trailingText: widget.results.pSeryNumber!),
                      const Divider(),
                      BetweenListItem(
                          title: S.of(context).payment_date,
                          trailingText: FrequentWidgets.dateTimeToLocal(
                              widget.results.pDate!)),

                      // const Divider(),
                      // BetweenListItem(
                      //     title: S.of(context).car,
                      //     trailingText: chequeDetailsResponse?.carModel != null
                      //         ? "${chequeDetailsResponse?.carModel.mark ?? ""} ${chequeDetailsResponse?.carModel.name ?? ""} "
                      //         : ""),
                      const SizedBox(
                        height: 24,
                      ),
                    ],
                  ),
                );
              }),
            ),
          ),
          Positioned(
            bottom: 12,
            left: 20,
            right: 20,
            child: buttonWidget(
                context, Icons.picture_as_pdf, S.of(context).download,
                () async {
              if (widget.results.pSeryNumber != null)
                await savePdf(context, widget.results.pSeryNumber!,
                    widget.results.pAmount!,
                    isShare: true);
            }),
          ),
        ],
      ),
    );
  }
}
