import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/enums/work_order_next_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/new_models/work_order_detail_model.dart';
import 'package:test_sa/modules/cm_module/cm_detail_provider.dart';
import 'package:test_sa/modules/cm_module/views/forms/asset_retired/asset_retired.dart';
import 'package:test_sa/modules/cm_module/views/forms/cost/cost_detail_form_screen.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/views/widgets/equipment/asset_detail_page.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.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 'package:test_sa/views/widgets/requests/request_status.dart';
import 'package:test_sa/views/widgets/sound/sound_player.dart';

import 'action_button/footer_action_button.dart';
import 'asset_detail_card.dart';
import 'initial_visit_card.dart';

class ServiceRequestDetailView extends StatefulWidget {
  ServiceRequestDetailView({Key? key}) : super(key: key);

  @override
  State<ServiceRequestDetailView> createState() => _ServiceRequestDetailViewState();
}

class _ServiceRequestDetailViewState extends State<ServiceRequestDetailView> {
  List<GenericAttachmentModel> _userAttachments = [];
  List<GenericAttachmentModel> _attachments = [];

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

  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context, listen: false);
    return Consumer<CMDetailProvider>(builder: (pContext, requestProvider, _) {
      if (userProvider.user?.type == UsersTypes.engineer) {
        _userAttachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments
            .whereType<GenericAttachmentModel>()
            .where((e) => e.createdBy == userProvider.user?.userID)
            .map((e) => GenericAttachmentModel(id: e.id, name: e.name, createdBy: e.createdBy, documentType: e.documentType))
            .toList() ?? [];
        _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments
            .whereType<GenericAttachmentModel>()
            .where((e) => e.createdBy != userProvider.user?.userID)
            .toList() ?? [];
      } else {
        _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments
            .whereType<GenericAttachmentModel>()
            .where((e) => e.createdBy == userProvider.user?.userID)
            .toList() ?? [];
      }

      bool showInitialVisitCard = requestProvider.currentWorkOrder?.data?.needAVisitDateTime != null &&
          userProvider.user?.type == UsersTypes.engineer &&
          requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.eArrived;
      bool showAssetDetailCard = (userProvider.user?.type == UsersTypes.engineer && requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity) ||
          requestProvider.isReadOnlyRequest;
      bool showCostCard = context.userProvider.user!.type == UsersTypes.engineer &&
          !requestProvider.isReadOnlyRequest &&
          requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity;

      return requestProvider.isLoading
          ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
          : requestProvider.currentWorkOrder == null
              ? const NoDataFound()
              : Column(
                  children: [
                    SingleChildScrollView(
                      padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          workOrderDetailCard(context, requestProvider.currentWorkOrder!.data!, userProvider, requestProvider),
                          if (showInitialVisitCard) ...[
                            16.height,
                            const InitialVisitCard(),
                            // initialVisitCard(requestDetailProvider: requestProvider, userProvider: _userProvider),
                          ],
                          if (showAssetDetailCard) ...[
                            16.height,
                            assetDetailCard(requestDetailProvider: requestProvider, userProvider: userProvider),
                          ],
                          if (showCostCard) ...[
                            16.height,
                            costCard(context, requestProvider),
                          ],
                          16.height,
                          contactInfoCard(context, requestProvider.currentWorkOrder!.data!),
                          20.height,
                        ],
                      ),
                    ).expanded,
                    SafeArea(
                      top: false,
                      right: false,
                      left: false,
                      child: FooterActionButton.requestDetailsFooterWidget(
                          workOrderNextStepStatus: requestProvider.currentWorkOrder!.data!.nextStep!.workOrderNextStepEnum!,
                          status: requestProvider.currentWorkOrder?.data?.status,
                          isEmpIsAssigned: requestProvider.currentWorkOrder!.data!.assignedEmployee != null,
                          activities: requestProvider.currentWorkOrder!.data?.activities ?? [],
                          userProvider: userProvider,
                          context: context),
                    )
                  ],
                );
    });
  }

  Widget workOrderDetailCard(BuildContext context, WorkOrderData workOrder, UserProvider userProvider, CMDetailProvider requestProvider) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Wrap(
                          // spacing: 8,
                          runSpacing: 8,
                          children: [
                            if (Provider.of<SettingProvider>(context, listen: false).showPriority && workOrder.priority != null) ...[
                              StatusLabel(
                                label: workOrder.priority?.name,
                                id: workOrder.priority?.value,
                                radius: 4,
                                textColor: AppColor.getPriorityStatusTextColor(context, workOrder.priority!.value!),
                                backgroundColor: AppColor.getPriorityStatusColor(context, workOrder.priority!.value!),
                              ),
                              8.width,
                            ],
                            if (workOrder.itgFormWorkOrderStatus != null) ...[
                              StatusLabel(
                                label: workOrder.itgFormWorkOrderStatus,
                                // id: 0,
                                radius: 4,
                                textColor: AppColor.getPriorityStatusTextColor(context, 82),
                                backgroundColor: AppColor.getPriorityStatusColor(context, 1000),
                              ),
                              8.width,
                            ],
                            StatusLabel(
                              radius: 4,
                              label: workOrder.status!.name,
                              textColor: AppColor.getHistoryLogStatusTextColorByName(context, workOrder.status!.name!),
                              backgroundColor: AppColor.getHistoryLogStatusColorByName(context, workOrder.status!.name!),
                            ),
                            if (workOrder.since != null) ...[
                              8.width,
                              StatusLabel(
                                radius: 4,
                                label: '${workOrder.since} days',
                                textColor: AppColor.yellowStatusTextColor,
                                backgroundColor: AppColor.yellowStatusColor,
                              ),
                            ],
                          ],
                        ).expanded,
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            // if (userProvider.user!.type == UsersTypes.normal_user)
                            //   context.translation.code.toSvgAsset(width: 48).onPress(() {
                            //     // Navigator.push(context, MaterialPageRoute(builder: (context) => UpdateServiceRequestPage(serviceRequest: serviceRequest)));
                            //   }),
                            // if (userProvider.user!.type == UsersTypes.engineer) 16.height,
                            InfoDateWidget(workOrder.requestedDate?.toString() ?? ""),
                          ],
                        )
                      ],
                    ),
                    8.height,
                    Row(
                      spacing: 4,
                      children: [
                        Flexible(
                          child: InfoHeader16Widget(context.translation.assetInformation),
                        ),
                        const Icon(Icons.open_in_new_rounded, color: AppColor.primary10, size: 16).onPress(() {
                          Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: workOrder.asset!.id);
                        })
                      ],
                    ),
                    if (context.userProvider.isEngineer && !(workOrder.asset!.hasTrainingImageData ?? true)) ...[
                      InfoTextLabelWidget(label: '*Images are required for the asset', color: AppColor.red30, textStyle: AppTextStyles.tinyFont2),
                      4.height,
                    ],
                    InfoTextWidget(label: context.translation.assetName, value: workOrder.assetNdModel!.name?.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.assetNumber, value: workOrder.asset!.assetNumber, copyValue: true),
                    InfoTextWidget(label: context.translation.serialNo, value: workOrder.asset!.assetSerialNo),
                    InfoTextWidget(label: context.translation.manufacture, value: workOrder.manufacturer?.name?.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.model, value: workOrder.model?.name!.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.assetType, value: workOrder.assetType?.name!.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.site, value: workOrder.site?.siteName?.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.building, value: workOrder.building?.name?.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.floor, value: workOrder.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach ?? ""),
                    InfoTextWidget(label: context.translation.department, value: workOrder.department?.name?.cleanupWhitespace.capitalizeFirstOfEach),
                    InfoTextWidget(label: context.translation.room, value: (workOrder.room?.name ?? "").cleanupWhitespace.capitalizeFirstOfEach),
                  ],
                ).expanded,
              ],
            ),
            const Divider().defaultStyle(context),

            //... request details starts here....
            InfoHeader16Widget(context.translation.callDetails),
            InfoTextWidget(label: context.translation.cmNumber, value: workOrder.workOrderNo, copyValue: true),
            InfoTextWidget(label: context.translation.createdBy, value: workOrder.workOrderCreatedBy?.userName ?? "-"),
            InfoTextWidget(label: context.translation.arrivedDate, value: workOrder.iHaveArrivedDate != null ? workOrder.iHaveArrivedDate.toString().toServiceRequestDetailsFormat : '-'),
            InfoTextWidget(label: context.translation.closedDate, value: workOrder.closedDate != null ? workOrder.closedDate!.toString().toServiceRequestDetailsFormat : '-'),
            if (workOrder.problemDescription != null) InfoTextWidget(label: context.translation.problemDesc, value: workOrder.problemDescription?.name ?? ""),

            const Divider().defaultStyle(context),

            //... call response details starts here....
            InfoHeader16Widget(context.translation.callResponse),
            InfoTextWidget(label: context.translation.assignedTo, value: workOrder.assignedEmployee?.userName ?? '-'),
            InfoTextWidget(label: context.translation.assetStatus, value: workOrder.equipmentStatus?.name ?? "-"),
            InfoTextWidget(label: context.translation.activityStatus, value: workOrder.lastActivityStatus?.name ?? "-"),
            InfoTextWidget(label: context.translation.callResponse, value: workOrder.callResponse ?? "-"),

            if (workOrder.rejectReason != null) ...[
              const Divider().defaultStyle(context),
              InfoHeader16Widget(context.translation.rejectionDetails),
              InfoTextWidget(label: context.translation.rejectionReason, value: workOrder.rejectReason?.name ?? '-'),
              InfoTextWidget(label: context.translation.comment, value: workOrder.rejectComment ?? '-'),
            ],
            if ((workOrder.comments ?? "").isNotEmpty) ...[
              const Divider().defaultStyle(context),
              InfoHeader16Widget(context.translation.callComments),
              8.height,
              Text(
                workOrder.comments!,
                style: AppTextStyles.bodyText2.copyWith(color: AppColor.labelTextStyleColor(context)),
              ),
            ],
            if (userProvider.user?.type == UsersTypes.engineer) ...[
              if (_attachments.isNotEmpty) ...[
                const Divider().defaultStyle(context),
                InfoHeader16Widget("Attachments".addTranslation),
                FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()),
              ],
              if (!requestProvider.isReadOnlyRequest && workOrder.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity) ...[
                const Divider().defaultStyle(context),
                AttachmentPicker(
                  label: context.translation.attachments,
                  showAsListView: true,
                  attachment: _userAttachments,
                  buttonColor: AppColor.primary10,
                  onlyImages: false,
                  buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10),
                  onChange: (attachment) {
                    requestProvider.addWorkOrderAttachment(woId: workOrder.requestId!, attachments: attachment, otherAttachment: _attachments,);
                  },
                ),
              ],
            ] else ...[
              if (_attachments.isNotEmpty) ...[
                const Divider().defaultStyle(context),
                FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList(),showAsListView: true,),
              ],
              //handle nurse case..
            ],

            if (workOrder.voiceNote?.isNotEmpty ?? false) ...[
              const Divider().defaultStyle(context),
              ASoundPlayer(audio: URLs.getFileUrl(workOrder.voiceNote!)!),
            ],
          ],
        ),
        if ((workOrder.nextStep!.workOrderNextStepEnum == WorkOrderNextStepEnum.verifyAssetDetail || workOrder.nextStep!.workOrderNextStepEnum == WorkOrderNextStepEnum.activity) &&
            userProvider.user?.type == UsersTypes.engineer) ...[
          8.height,
          assetRetiredButton(context: context),
        ]
      ],
    ).toShadowContainer(context);
  }

  Widget contactInfoCard(BuildContext context, WorkOrderData workOrder) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoHeader16Widget("Contact Info"),
        ListView.separated(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            padding: EdgeInsets.zero,
            itemBuilder: (cxt, index) => Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    InfoTextWidget(label: 'Name'.addTranslation, value: workOrder.workOrderContactPerson[index].name ?? '-'),
                    InfoTextWidget(label: context.translation.employeeId, value: workOrder.workOrderContactPerson[index].employeeId ?? '-'),
                    InfoTextWidget(label: context.translation.telephone, value: workOrder.workOrderContactPerson[index].mobilePhone ?? '-'),
                    InfoTextWidget(label: 'Job'.addTranslation, value: workOrder.workOrderContactPerson[index].position ?? '-'),
                    InfoTextWidget(label: context.translation.email, value: workOrder.workOrderContactPerson[index].email ?? '-'),
                    InfoTextWidget(label: 'Extension'.addTranslation, value: workOrder.workOrderContactPerson[index].extension ?? '-'),
                  ],
                ),
            separatorBuilder: (cxt, index) => const Divider().defaultStyle(context),
            itemCount: workOrder.workOrderContactPerson.length),
      ],
    ).toShadowContainer(context);
  }

  Widget costCard(BuildContext context, CMDetailProvider provider) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            InfoHeader16Widget("Cost"),
            const Spacer(),
            if (!provider.isReadOnlyRequest)
              "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async {
                provider.refreshTimer = false;
                await Navigator.push(context, MaterialPageRoute(builder: (context) => CostDetailFormScreen(isEdit: true)));
                provider.refreshTimer = true;
              }),
          ],
        ),
        InfoTextWidget(label: 'Spare Part Cost'.addTranslation, value: provider.currentWorkOrder?.data?.sparePartCost?.toString() ?? '-'),
        InfoTextWidget(label: 'Labor Cost'.addTranslation, value: provider.currentWorkOrder?.data?.labourCost?.toString() ?? '-'),
        InfoTextWidget(label: 'Travel Cost'.addTranslation, value: provider.currentWorkOrder?.data?.travelCost?.toString() ?? '-'),
        InfoTextWidget(label: 'Quot Amount'.addTranslation, value: provider.currentWorkOrder?.data?.qAmount?.toString() ?? '-'),
        InfoTextWidget(label: 'PR No'.addTranslation, value: provider.currentWorkOrder?.data?.prNo?.toString() ?? '-'),
        InfoTextWidget(label: 'PO No'.addTranslation, value: provider.currentWorkOrder?.data?.poNo?.toString() ?? '-'),
        InfoTextWidget(label: 'MR No'.addTranslation, value: provider.currentWorkOrder?.data?.mrNo?.toString() ?? '-'),
        InfoTextWidget(label: 'Exchange Cost'.addTranslation, value: provider.currentWorkOrder?.data?.exchangeCost?.toString() ?? '-'),
      ],
    ).toShadowContainer(context);
  }

  Widget assetRetiredButton({required BuildContext context}) {
    return AppFilledButton(
        label: context.translation.assetToBeRetired,
        maxWidth: true,
        buttonColor: AppColor.background(context),
        textColor: AppColor.red30,
        showBorder: true,
        onPressed: () async {
          Navigator.push(context, MaterialPageRoute(builder: (context) => const AssetRetired()));
        });
  }

  Widget initialVisitCard({required CMDetailProvider requestDetailProvider, required UserProvider userProvider}) {
    if (requestDetailProvider.currentWorkOrder!.data!.needAVisitDateTime != null &&
        userProvider.user?.type == UsersTypes.engineer &&
        requestDetailProvider.currentWorkOrder?.data?.nextStep!.workOrderNextStepEnum == WorkOrderNextStepEnum.eArrived) {
      return const InitialVisitCard();
    } else {
      return const SizedBox();
    }
  }

  Widget assetDetailCard({required CMDetailProvider requestDetailProvider, required UserProvider userProvider}) {
    WorkOrderData currentWorkOrderData = requestDetailProvider.currentWorkOrder!.data!;
    requestDetailProvider.engineerUpdateWorkOrderHelperModel = EngineerUpdateWorkOrderHelperModel(
      workOrderId: currentWorkOrderData.requestId,
      equipmentStatus: currentWorkOrderData.equipmentStatus,
      loanAvailability: currentWorkOrderData.loanAvailablity,
      failureReason: currentWorkOrderData.failureReasone,
      faultDescription: currentWorkOrderData.faultDescription,
      solution: currentWorkOrderData.faultDescription?.workPerformed,
      returnToService: currentWorkOrderData.returnToService,
      serviceType: currentWorkOrderData.serviceType,
      descriptionOfFinding: currentWorkOrderData.descriptionOfFinding,
      actionTaken: currentWorkOrderData.actionTaken,
      edd: currentWorkOrderData.edd,
      cmFrameId: currentWorkOrderData.cmFrame,
    );
    return const AssetDetailCard();
  }
}
