import 'dart:async';
import 'dart:developer';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/general_models/generic_resp_model.dart';
import 'package:mc_common_app/models/provider_branches_models/profile/document.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/view_models/service_view_model.dart';
import 'package:mc_common_app/views/advertisement/ad_creation_steps/ad_creation_steps_containers.dart';
import 'package:mc_common_app/views/advertisement/components/picked_images_container_widget.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.dart';
import 'package:mc_common_app/widgets/common_widgets/search_entity_widget.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';

import 'package:mc_common_app/widgets/txt_field.dart';
import 'package:provider/provider.dart';

class ProviderLicensePage extends StatefulWidget {
  const ProviderLicensePage({super.key});

  @override
  State<ProviderLicensePage> createState() => _ProviderLicensePageState();
}

class _ProviderLicensePageState extends State<ProviderLicensePage> {
  late ServiceVM branchVM;
  bool showAttachment = false;
  String? attachedFile;
  String? formattedDate;

  @override
  void initState() {
    super.initState();
    scheduleMicrotask(() async {
      final serviceVm = context.read<ServiceVM>();
      await serviceVm.getServiceProviderDocument(AppState().getUser.data!.userInfo!.providerId ?? 0);
    });
  }

  bool isAllowContinue(ServiceVM model) {
    bool isShow = false;
    if (model.document != null && model.document!.data != null && model.document!.data!.isNotEmpty) {
      for (var doc in model.document!.data!) {
        log("doc: ${doc.status}");
        if (doc.status == DocumentStatusEnum.rejected || doc.status == DocumentStatusEnum.needUpload || doc.isAllowUpdate!) {
          isShow = true;
        }
      }
    }
    return isShow;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.defineLicences.tr(),
        isRemoveBackButton: false,
      ),
      body: Consumer<ServiceVM>(builder: (_, serviceVM, __) {
        if (serviceVM.state == ViewState.busy) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        return GestureDetector(
          onTap: () =>
              FocusScope
                  .of(context)
                  .focusedChild!
                  .unfocus(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: SingleChildScrollView(child: buildContent(serviceVM)),
              ),
              if (isAllowContinue(serviceVM)) ...[
                Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: ShowFillButton(
                    title: LocaleKeys.continu.tr(),
                    maxWidth: double.infinity,
                    onPressed: () async {
                      bool status = false;
                      if (AppState().getUser.data!.userInfo!.roleId == 5) {
                        if (validateDocuments(serviceVM)) {
                          status = await updateDocument(serviceVM);
                        } else {
                          Utils.showToast(LocaleKeys.allDocumentMandatoryDealershipProvider.tr());
                          return;
                        }
                      } else {
                        status = await updateDocument(serviceVM);
                      }
                      Future.delayed(const Duration(seconds: 1), () {
                        if (status) {
                          pop(context);
                        }
                      });
                    },
                  ),
                ),
              ],
            ],
          ),
        );
      }),
    );
  }

  validateDocuments(ServiceVM model) {
    bool valid = true;
    for (var element in model.document!.data!) {
      log("documentUrl: ${element.documentUrl}");
      if (element.documentUrl == null) {
        valid = false;
      }
    }
    return valid;
  }

  Future<bool> updateDocument(ServiceVM model) async {
    try {
      Utils.showLoading(context);
      GenericRespModel res = await model.updateDocument(model.document!.data);
      Utils.hideLoading(context);
      if (res.messageStatus == 1) {
        Utils.showToast(LocaleKeys.documentsUploadedSuccessfully.tr());
        Navigator.of(context).pop();
        return true;
      } else {
        Utils.showToast(res.message ?? "");
        return false;
      }
    } catch (e, s) {
      return false;
    }
  }

  Widget buildContent(ServiceVM serviceVM) {
    if (serviceVM.document == null) {
      return Center(child: CircularProgressIndicator());
    }
    return serviceVM.document!.data!.isEmpty
        ? Text(LocaleKeys.somethingWrong.tr())
        : ListView.separated(
      separatorBuilder: (context, index) {
        return 20.height;
      },
      itemCount: serviceVM.document!.data!.length,
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: const EdgeInsets.symmetric(horizontal: 20),
      itemBuilder: (context, index) {
        DocumentData? document = serviceVM.document?.data![index];

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            10.height,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                (document!.documentName!).toText(fontSize: 16, letterSpacing: -0.56, fontWeight: MyFonts.SemiBold),
                if (document.statusText != null && document.statusText!.isNotEmpty) ...[
                  10.width,
                  Utils.statusContainerChip(text: document.statusText!.replaceFirst('OrActive', ''), chipColor: getColorByStatus(document.status!)),
                ],
              ],
            ),
            if (document.documentUrl != null) ...[
              BuildFilesContainer(
                image: ImageModel(id: index, filePath: document.documentUrl!, isFromNetwork: document.isLocalFile! ? false : true),
                onCrossPressedPrimary: (String val) {
                  document.documentUrl = null;
                  document.isLocalFile = false;
                  setState(() {});
                },
                index: index,
                isReview: isReview(document),
                isPdf: true,
              ),
              5.height,
              ("${document.documentName} Expiry").toText(fontSize: 14, letterSpacing: -0.56, fontWeight: MyFonts.Medium),
              5.height,
              TxtField(
                isBackgroundEnabled: (document.status == DocumentStatusEnum.pending || document.status == DocumentStatusEnum.approvedOrActive && !document.isAllowUpdate!),
                isNeedBorder: document.isAllowUpdate! ? true : false,
                isSidePaddingZero: true,

                hint: LocaleKeys.expiryDate.tr(),
                value: document.dateExpire != null && document.status == DocumentStatusEnum.pending || document.status == DocumentStatusEnum.approvedOrActive ? "${DateFormat('yyyy-MM-dd').format(
                    DateTime.parse(document.dateExpire!))}" : formattedDate == null
                    ? ""
                    : "${DateFormat('yyyy-MM-dd').format(DateTime.parse(document.dateExpire!))}",
                isNeedClickAll: true,
                postFixDataColor: MyColors.darkTextColor,
                onTap: () async {
                  if (document.isAllowUpdate! && document.status == DocumentStatusEnum.approvedOrActive || document.status == DocumentStatusEnum.needUpload ||
                      document.status == DocumentStatusEnum.rejected) {
                    formattedDate =
                    await Utils.pickDateFromDatePicker(context, lastDate: DateTime(DateTime
                        .now()
                        .year + 3, DateTime
                        .now()
                        .month + 1, DateTime
                        .now()
                        .day), firstDate: DateTime.now());
                    if (formattedDate!.isNotEmpty) {
                      document.dateExpire = formattedDate;
                      setState(() {});
                    }
                  }

                  // requestsVM.updateRequestedDate(formattedDate);
                },
              ),
              10.height,
              buildCommentContainer(document: document),
            ] else
              ...[
                10.height,
                DottedRectContainer(
                  onTap: () => serviceVM.pickPdfReceiptFile(context, document.documentId!, index) ?? "",
                  text: LocaleKeys.attachPDF.tr(),
                  icon: MyAssets.attachmentIcon.buildSvg(),
                  extensions: GlobalConsts.allowedFileExtensionsPDF,
                ),
              ]
          ],
        );
      },
    );
  }

  bool isReview(DocumentData document) {
    print(document.toJson());
    bool val = false;
    if (document.isAllowUpdate == null) {
      val = false;
    }
    if (document.isAllowUpdate! && document.status == DocumentStatusEnum.approvedOrActive) {
      val = false;
    }
    if (!document.isAllowUpdate! && document.status == DocumentStatusEnum.approvedOrActive) {
      val = true;
    }
    if (document.isAllowUpdate! && document.status == DocumentStatusEnum.pending) {
      val = true;
    }
    if (document.isAllowUpdate! && document.status == DocumentStatusEnum.rejected) {
      val = false;
    }
    if (document.isAllowUpdate! && document.status == DocumentStatusEnum.needUpload) {
      val = true;
    }
    if (document.isAllowUpdate! && document.status == DocumentStatusEnum.review) {
      val = true;
    }

    return val;
  }

// List<ImageModel> isLocalOrNetworkFiles({required ServiceVM model, required DocumentData document}) {
//   bool isNetworkImage = false;
//   print(document);
//   if (!document.isLocalFile!) {
//     isNetworkImage = document.documentUrl != null && document.documentUrl!.isNotEmpty ? true : false;
//   }
//   if (isNetworkImage) {
//     return [ImageModel(id: document.id, isFromNetwork: isNetworkImage, filePath: document.documentUrl)];
//   } else {
//     return [ImageModel(id: document.id, isFromNetwork: false, filePath: document.documentUrl)];
//     ;
//   }
// }

// bool isNeedToShow({required ServiceVM model, required DocumentData document}) {
//   bool allow = false;
//   bool isNetworkImage = document.documentUrl != null && document.documentUrl!.isNotEmpty && !(document.isLocalFile ?? true);
//   if (isNetworkImage) {
//     allow = true;
//   } else {
//     if (document.documentId == 1 && document.documentUrl!.isNotEmpty) {
//       allow = true;
//     }
//     if (document.documentId == 2 && document.documentUrl!.isNotEmpty) {
//       allow = true;
//     }
//     if (document.documentId == 3 && document.documentUrl!.isNotEmpty) {
//       allow = true;
//     }
//   }
//   return allow;
// }
//
// dynamic checkOnCrossPress({required ServiceVM model, required DocumentData document}) async {
//   bool isNetworkImage = document.documentUrl != null && document.documentUrl!.isNotEmpty ? true : false;
//   if (isNetworkImage) {
//     print(document.documentUrl);
//     return document.documentUrl;
//   }

//} else {
// if (document.documentId == 1) {
//   model.commerceRemove;
// }
// if (document.documentId == 2) {
//   model.commercialRemove;
// }
// if (document.documentId == 3) {
//   model.vatRemove;
// }
//  }
}

bool isNetworkImage({required DocumentData document}) {
  bool isNetworkImage = false;
  if (!document.isLocalFile!) {
    isNetworkImage = document.documentUrl != null && document.documentUrl!.isNotEmpty ? true : false;
  }
  return isNetworkImage;
}

Widget buildCommentContainer({required DocumentData document}) {
  String comment = "";
  if (document.status == 4 && document.comment != null) {
    comment = document.comment ?? "";
  }

  if (comment.isEmpty) {
    return const SizedBox();
  }
  return Center(child: comment.toString().toText(color: MyColors.adCancelledStatusColor, fontSize: 14)).toContainer(
    borderRadius: 8,
    margin: const EdgeInsets.only(top: 10),
    width: double.infinity,
    backgroundColor: MyColors.adCancelledStatusColor.withOpacity(0.16),
  );
}

Color getColorByStatus(DocumentStatusEnum docStatus) {
  switch (docStatus) {
    case DocumentStatusEnum.pending:
      return MyColors.adPendingStatusColor;

    case DocumentStatusEnum.approvedOrActive:
      return MyColors.adActiveStatusColor;

    case DocumentStatusEnum.rejected:
      return MyColors.adCancelledStatusColor;

    case DocumentStatusEnum.needUpload:
      return MyColors.adPendingStatusColor;
    default:
      return MyColors.adPendingStatusColor;
  }
}
