import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/enums/demo_request_step.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/module_permissions_model.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/demo_module/demo_extension_bottom_sheet.dart';
import 'package:test_sa/modules/demo_module/models/demo_request_model.dart';
import 'package:test_sa/modules/demo_module/provider/demo_provider.dart';
import 'package:test_sa/modules/loan_module/models/loan_attachment_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/swipe_module/dialoge/acknowledge_work_dialog.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

import '../../controllers/api_routes/urls.dart';
import '../../extensions/text_extensions.dart';
import '../../new_views/common_widgets/default_app_bar.dart';
import '../../views/widgets/images/files_list.dart';
import '../../views/widgets/requests/request_status.dart';
import '../loan_module/models/loan_request_model.dart';
import 'demo_activities_page.dart';
import 'models/demo_attachment_model.dart';

class DemoDetailViewPage extends StatefulWidget {
  static const String id = "/demo-detail-page";
  final int demoId;
  final int moduleId;

  DemoDetailViewPage({Key? key, required this.demoId, required this.moduleId}) : super(key: key);

  @override
  _DemoDetailViewPageState createState() {
    return _DemoDetailViewPageState();
  }
}

class _DemoDetailViewPageState extends State<DemoDetailViewPage> {
  // bool isLoading = false;

  // DemoRequestModel? dataModel;
  DemoProvider? demoProvider;

  // List<DemoAttachments> allAttachments = [];

  //Todo need to check about attachments.

  ModulesPermissionsModel? modelPermission;

  @override
  void initState() {
    demoProvider = Provider.of<DemoProvider>(context, listen: false);
    modelPermission = context.userProvider.currentModelPermission(widget.moduleId);
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   getDetailsById();
    // });
    super.initState();
  }

  // Future<void> getDetailsById() async {
  //   setState(() {
  //     loading = true;
  //   });
  //   dataModel = await demoProvider?.getDemoById(widget.demoId);// ?? DemoRequestModel();
  //
  //   allAttachments = dataModel?.demoAttachments ?? [];
  //   setState(() {
  //     loading = false;
  //   });
  // }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(title: "Request Details"),
        body: FutureBuilder<DemoRequestModel?>(
            future: Provider.of<DemoProvider>(context, listen: false).getDemoById(widget.demoId),
            builder: (BuildContext context, AsyncSnapshot<DemoRequestModel?> snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center;
              if (snapshot.data == null) return const NoDataFound().center;

              List<GenericAttachmentModel> allAttachments = snapshot.data!.demoAttachments! ?? [];
              List<GenericAttachmentModel> suppAttachments = snapshot.data!.supplierDemoAttachments! ?? [];

              DemoRequestModel demoData = snapshot.data!;

              return Column(
                children: [
                  SingleChildScrollView(
                    padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 56),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (demoData.status != null) ...[
                          StatusLabel(
                            label: context.userProvider.isNurse ? demoData.endUserStatus?.name : demoData.status?.name,
                            id: demoData.status?.value,
                            radius: 4,
                            textColor: AppColor.demoRequestStatusTextColor(context, context.userProvider.isNurse ? demoData.endUserStatus!.value! : demoData.status!.value!),
                            backgroundColor: AppColor.demoRequestStatus(context, context.userProvider.isNurse ? demoData.endUserStatus!.value! : demoData.status!.value!),
                          ),
                          8.height,
                        ],
                        ...requesterDetails(context, demoData),
                        const Divider().defaultStyle(context),
                        ...requestDetails(context, demoData),
                        const Divider().defaultStyle(context),
                        ...doctorDetails(context, demoData),
                        const Divider().defaultStyle(context),
                        ...assetDetails(context, demoData),
                        const Divider().defaultStyle(context),
                        ...vendorDetails(context, demoData),
                        if (allAttachments.isNotEmpty) ...[
                          const Divider().defaultStyle(context),
                          InfoHeader16Widget("Attachments"),
                          FilesList(
                              showAsListView: true,
                              images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(),
                              types: allAttachments.map((e) => e.documentType?.name ?? '').toList()),
                        ],
                        if (suppAttachments.isNotEmpty) ...[
                          const Divider().defaultStyle(context),
                          InfoHeader16Widget("Supplier Attachments"),
                          FilesList(
                              showAsListView: true,
                              images: suppAttachments.whereType<GenericAttachmentModel>().map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(),
                              types: suppAttachments.whereType<GenericAttachmentModel>().map((e) => e.documentType?.name ?? '').toList()),
                        ],
                      ],
                    ).toShadowContainer(context, padding: 12),
                  ).expanded,
                  if (modelPermission?.canEdit ?? false)
                    if (context.userProvider.isNurse && context.settingProvider.isUserFlowMedical && (demoData.status!.value == 2))
                      FooterActionButton.footerContainer(
                        context: context,
                        child: AppFilledButton(
                          label: context.translation.cancel,
                          buttonColor: AppColor.white60,
                          textColor: AppColor.black10,
                          loading: false,
                          onPressed: () async {
                            showDialog(
                              context: context,
                              builder: (BuildContext cxt) => AcknowledgeWorkDialog(
                                message: "Are you sure, you want to cancel request?",
                                confirmButtonText: 'Confirm',
                                cancelButtonText: 'Cancel',
                                onSave: () async {
                                  Utils.showLoading(context);
                                  DemoProvider demoProvider = Provider.of<DemoProvider>(context, listen: false);
                                  bool isSuccess = await demoProvider.cancelRequest(demoData.id!);
                                  Utils.hideLoading(context);
                                  if (isSuccess) {
                                    setState(() {});
                                  }
                                },
                                onDiscard: () {},
                              ),
                            );
                          },
                        ),
                      )
                    else
                      FooterActionButton.demoRequestDetailsFooterWidget(
                          demoRequestStage: demoData.status!.demoRequestStepEnum!,
                          dataModel: demoData,
                          status: demoData.status!,
                          context: context,
                          refreshData: () => setState(() {})).toShadowContainer(context, padding: 0, showShadow: false, borderRadius: 0),
                ],
              );
            }));
  }

  List<Widget> requestDetails(BuildContext context, DemoRequestModel? model) {
    return [
      InfoHeader16Widget("Request Information"),
      InfoTextWidget(label: "Request No", value: model?.requestNo ?? "-", copyValue: true),
      InfoTextWidget(label: "Demo No", value: model?.demoNo ?? "-"),
      InfoTextWidget(label: "Demo Period", value: model?.demoPeriod?.name ?? "-"),
      InfoTextWidget(label: context.translation.site, value: model?.site?.custName ?? "-"),
      InfoTextWidget(label: context.translation.building, value: model?.building?.name ?? "-"),
      InfoTextWidget(label: context.translation.floor, value: model?.floor?.name ?? "-"),
      InfoTextWidget(label: context.translation.department, value: model?.department?.departmentName ?? "-"),
      InfoTextWidget(label: "Item Description", value: model?.itemDescription ?? "-"),
      InfoTextWidget(label: "Request Description", value: model?.requestDescription ?? "-"),
    ];
  }

  List<Widget> vendorDetails(BuildContext context, DemoRequestModel? model) {
    return [
      InfoHeader16Widget("Vendor Information"),
      InfoTextWidget(label: "Name", value: model?.supplier?.name ?? model?.vendorName ?? "-"),
      InfoTextWidget(label: "Representative Name", value: model?.suppPerson?.name ?? model?.vendorRepresentativeName ?? "-"),
      InfoTextWidget(label: "Contact", value: model?.supplier?.contact ?? model?.vendorContactNumber ?? "-"),
      InfoTextWidget(label: "Email", value: model?.supplier?.email ?? model?.vendorEmail ?? "-"),
    ];
  }

  List<Widget> assetDetails(BuildContext context, DemoRequestModel? model) {
    return [
      InfoHeader16Widget("Asset Information"),
      InfoTextWidget(label: context.translation.assetName, value: model?.assetName ?? "-"),
      InfoTextWidget(label: context.translation.manufacture, value: model?.manufacturer ?? "-"),
      InfoTextWidget(label: context.translation.model, value: model?.model ?? "-"),
    ];
  }

  List<Widget> doctorDetails(BuildContext context, DemoRequestModel? model) {
    return [
      InfoHeader16Widget("Doctor Information"),
      InfoTextWidget(label: "Name", value: model?.doctorName ?? "-"),
      InfoTextWidget(label: "Contact", value: model?.doctorContactNumber ?? "-"),
      InfoTextWidget(label: "Email", value: model?.doctorContactEmail ?? "-"),
    ];
  }

  List<Widget> requesterDetails(BuildContext context, DemoRequestModel? model) {
    return [
      InfoHeader16Widget("Requester Information"),
      InfoTextWidget(label: "Name", value: model?.requesterUser?.requesterName ?? "-"),
      InfoTextWidget(label: "Email", value: model?.requesterUser?.requesterEmail ?? "-"),
      InfoTextWidget(label: "Contact", value: model?.requesterUser?.requesterMobile ?? "-"),
      // 'Extension: ${loanData.requesterExtensionNo ?? "-"}'.bodyText(context),
    ];
  }

  void _update() {}
}
