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/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;

  @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 == 4 || doc.status == 0) {
          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 ?? 1)),
                ],
              ],
            ),
            // if (document.status != 1 && document.status != 3) ...[
            //   Padding(
            //     padding: const EdgeInsets.only(top: 4, bottom: 8),
            //     child: LocaleKeys.enter_licence_detail.tr().toText(fontSize: 14, color: MyColors.lightTextColor),
            //   ),
            //   TxtField(
            //     hint: LocaleKeys.description.tr(),
            //     maxLines: 3,
            //     isBackgroundEnabled: true,
            //   ),
            // ],
            10.height,
            if (isNeedToShow(model: serviceVM, document: document)) ...[
              PickedFilesContainer(
                isReview: document.status != 0 && (document.status == 1 || document.status == 3),
                allowAdButton: false,
                pickedFiles: isLocalOrNetworkFiles(model: serviceVM, document: document),
                onCrossPressedPrimary: isNetworkImage(document: document)
                    ? serviceVM.removeNetworkImage
                    : document.documentId == 1
                    ? serviceVM.commerceRemove
                    : document.documentId == 2
                    ? serviceVM.commercialRemove
                    : serviceVM.vatRemove,
                isPdf: true,
                isFromNetwork: !(document.isLocalFile ?? false),
                onAddFilePressed: () {
                  serviceVM.pickPdfReceiptFile(context, document.documentId!, index);
                },
              ),
              buildCommentContainer(document: document),
            ] else
              ...[
                10.height,
                DottedRectContainer(
                  onTap: () => serviceVM.pickPdfReceiptFile(context, document.documentId!, index) ?? "",
                  text: LocaleKeys.attachPDF.tr(),
                  icon: MyAssets.attachmentIcon.buildSvg(),
                ),
              ],
          ],
        );
      },
    );
  }

  List<ImageModel> isLocalOrNetworkFiles({required ServiceVM model, required DocumentData document}) {
    bool isNetworkImage = false;

    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 if (document.documentId == 1) {
      return model.commerceCertificates;
    } else if (document.documentId == 2) {
      return model.commercialCertificates;
    } else {
      return model.vatCertificates;
    }
  }

  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 && model.commerceCertificates.isNotEmpty) {
        allow = true;
      }
      if (document.documentId == 2 && model.commercialCertificates.isNotEmpty) {
        allow = true;
      }
      if (document.documentId == 3 && model.vatCertificates.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) {
      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(int docStatus) {
    switch (docStatus) {
      case 1:
        return MyColors.adPendingStatusColor;

      case 2:
        return MyColors.adActiveStatusColor;

      case 3:
        return MyColors.greenColor;

      case 4:
        return MyColors.adCancelledStatusColor;

      default:
        return MyColors.adPendingStatusColor;
    }
  }
}
