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/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/new_models/work_order_detail_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/service_request_latest/service_request_detail_provider.dart';
import 'package:test_sa/service_request_latest/utilities/service_request_utils.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class HistoryLogView extends StatelessWidget {
  const HistoryLogView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<ServiceRequestDetailProvider>(builder: (context, requestProvider, _) {
      return requestProvider.isLoading
          ? const CircularProgressIndicator(color: AppColor.primary10).center
          : (requestProvider.currentWorkOrder == null || (requestProvider.currentWorkOrder?.data?.workOrderHistory.isEmpty ?? true)
              ? const NoDataFound()
              : Stack(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 122.toScreenWidth),
                      child: const VerticalDivider(
                        color: AppColor.white40,
                        thickness: 2,
                        width: 20,
                        indent: 10,
                        endIndent: 10,
                      ),
                    ),
                    Builder(builder: (cxt) {
                      List<Widget> items = [];
                      String lastStatus = "";
                      DateTime? nextDate;
                      var workOrderHistory = requestProvider.currentWorkOrder!.data!.workOrderHistory;
                      bool isNurse = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.normal_user;
                      if(isNurse) {
                        workOrderHistory.removeWhere((element)=>element.step?.id==5617);
                      }
                      for (int i = 0; i < workOrderHistory.length; i++) {
                        var object = workOrderHistory[i];
                        String currentStatus = object.workorderStatus!.name!;
                        if (lastStatus.isEmpty) {
                          lastStatus = currentStatus;
                        }
                        if (lastStatus == currentStatus) {
                          if (i + 1 < workOrderHistory.length) {
                            nextDate = workOrderHistory[i + 1].date;
                            String timeDifference = ServiceRequestUtils.calculateTimeDifference(object.date!, nextDate!);
                            object.timeDifference = timeDifference;
                          } else {
                            object.timeDifference = ''; // Empty string for the last action
                          }
                          items.add(historyLogCard(cxt, object));
                        } else {
                          items.add(statusCard(cxt, lastStatus));
                          lastStatus = currentStatus;
                          if (i + 1 < workOrderHistory.length) {
                            nextDate = workOrderHistory[i + 1].date;
                            String timeDifference = ServiceRequestUtils.calculateTimeDifference(object.date!, nextDate!);
                            object.timeDifference = timeDifference;
                          } else {
                            object.timeDifference = ''; // Empty string for the last action
                          }
                          items.add(historyLogCard(cxt, object));
                        }
                      }
                      items.add(statusCard(cxt, lastStatus));
                      return SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(children: items),
                      );
                    }),
                  ],
                ));
    });
  }

  Widget historyLogCard(BuildContext context, WorkOrderHistory object) {
    String title =object.step!.name!;

    if(object.step!.value == 18 || object.step!.value == 27 || object.step!.value == 28) {
      title = object.activityStatus?.name ?? "";
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Align(
          alignment: Alignment.centerLeft,
          child: Text(
            object.date.toString().toServiceRequestCardFormat,
            textAlign: TextAlign.end,
            style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
          ),
        ).expanded,
        Expanded(
          flex: 2,
          //....
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (object.assetVerificationType?.value == 4 && object.photoVerfication != null) ...[
                Padding(
                  padding:  EdgeInsets.symmetric(vertical: 12.toScreenWidth),

                  child: InteractiveViewer(child: Image.network(URLs.getFileUrl(object.photoVerfication ?? '')!, height: 143.toScreenHeight)),
                ).onPress(() async {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (_) => Scaffold(
                        body: SafeArea(
                          child: Stack(
                            children: [
                              InteractiveViewer(child: Image.network(URLs.getFileUrl(object.photoVerfication ?? '')!)).center,
                              const ABackButton(),
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                }),
              ],
              title.bodyText(context).custom(color: AppColor.black10),
              object.timeDifference.isNotEmpty ? object.timeDifference.tinyFont(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120) : const SizedBox(),

            ],
          ),
        ),
      ],
    ).toShadowContainer(context, padding: 16).paddingOnly(bottom: 16);
  }

  Widget statusCard(BuildContext context, String status) {
    return SizedBox(
      width: 153.toScreenWidth,
      child: StatusLabel(
        radius: 4,
        label: statusText(status.toLowerCase()),
        labelInCenter: true,
        textColor: AppColor.getHistoryLogStatusTextColorByName(status),
        backgroundColor: AppColor.getHistoryLogStatusColorByName(status),
      ),
    ).paddingOnly(bottom: 16, start: 40);
  }

  String statusText(String status) {
    if (status == "new" || status == "open") {
      return "Open Request".addTranslation;
    } else if (status == "in progress") {
      return "Status update to In Progress".addTranslation;
    } else if (status == "closed") {
      return "Status update to Closed".addTranslation;
    } else if (status == "completed") {
      return "Status update to Completed".addTranslation;
    } else if (status == "fixed") {
      return "Status update to Fixed".addTranslation;
    } else if (status == "reject") {
      return "Status update to Rejected".addTranslation;
    } else
      return status;
  }
}

class HistoryLogModel {
  String message;
  DateTime date;
  String? status;
  Color? statusColor;

  HistoryLogModel({required this.message, required this.date, this.status, this.statusColor});
}
