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/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/helper_data_models/maintenance_request/activity_maintenance_model.dart';
import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart';
import 'package:test_sa/models/new_models/assistant_employee.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/models/service_request/spare_parts.dart';
import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart';
import 'package:test_sa/models/service_request/supplier_details.dart';
import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/maintenance_request_main.dart';
import 'package:test_sa/modules/cm_module/views/forms/spare_part/spare_part_request.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/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

import 'bottom_sheets/service_request_bottomsheet.dart';

class ActivitiesListView extends StatefulWidget {
  static const String id = "/activities-list";

  const ActivitiesListView({Key? key}) : super(key: key);

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

class _ActivitiesListViewState extends State<ActivitiesListView> {
  @override
  void initState() {
    super.initState();
  }

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

  List<Activities> reOrderActivities = [];

  List<Activities> activities = [];

  bool disableNewActivity = false;

  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
      appBar: DefaultAppBar(
        showHomeActionButton: true,
        title: context.translation.activities,
        // actions: [if (!showReorderView) IconButton(onPressed: () => activities.isEmpty ? null : setState(() => showReorderView = true), icon: const Icon(Icons.reorder_rounded))],
      ),
      //backgroundColor: const Color(0xfff8f9fb),
      body: Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider requestDetailProvider, child) {
        activities = requestDetailProvider.currentWorkOrder!.data!.activities;
        requestDetailProvider.lastVisitedRequestActivityId = (activities.isNotEmpty ? activities.last.id : -1)!;
        if (activities.isNotEmpty && (activities.last.activityStatus!.value == 14 || activities.last.activityStatus!.value == 19)) {
          disableNewActivity = true;
        } else {
          disableNewActivity = false;
        }

        return Column(
          children: [
            (activities.isEmpty && reOrderActivities.isEmpty)
                ? NoDataFound(message: context.translation.noDataFound).center.expanded
                : ListView.separated(
                    padding: const EdgeInsets.all(16),
                    itemCount: activities.length,
                    separatorBuilder: (czt, index) => 16.height,
                    itemBuilder: (context, index) {
                      if (activities[index].activityMaintenance != null) {
                        return maintenanceActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: activities[index]);
                      }
                      return sparePartActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: activities[index]);
                    },
                  ).expanded,
            if (userProvider.user!.type == UsersTypes.engineer &&
                (requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && requestDetailProvider.currentWorkOrder?.data?.status?.value != 3))
              FooterActionButton.footerContainer(
              context: context,
                  child: AppFilledButton(
                label: context.translation.createNewActivity,
                maxWidth: true,
                buttonColor: AppColor.primary10,
                loading: requestDetailProvider.isLoading,
                disableButton: disableNewActivity,
                onPressed: () async {
                  ServiceRequestBottomSheet.activityTypeBottomSheet(context: context);
                },
              ))
          ],
        );
      }),
    );
  }

  Widget sparePartActivityCard({required ServiceRequestDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) {
    bool showActionButtons = userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId &&
        userProvider.user!.type == UsersTypes.engineer &&
        requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 &&
        requestDetailProvider.currentWorkOrder?.data?.status?.value != 3;

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            StatusLabel(
              label: activity.activityStatus?.name,
              textColor: AppColor.white10,
              // textColor: AppColor.getHistoryLogStatusTextColorByName(activity.activityStatus!.name!),
              // backgroundColor: AppColor.getHistoryLogStatusColorByName(activity.activityStatus!.name!),
              backgroundColor: AppColor.primary10,
            ),
            // "drag_icon".toSvgAsset(height: 12, width: 23, color: AppColor.neutral160),
            if (showActionButtons)
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  "edit_icon".toSvgAsset(height: 21, width: 21).onPress(() {
                    editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
                  }),
                  24.width,
                  "delete_icon".toSvgAsset(height: 21, width: 21).onPress(() async {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    int status = await requestDetailProvider.deleteActivitySparePart(id: activity.id!, workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                    if (status == 200) {
                      await requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                      Navigator.pop(context);
                    } else {
                      Navigator.pop(context);
                    }
                  }),
                ],
              )
          ],
        ),
        6.height,
//activity type...
        Text(
          '${activity.activityType?.cleanupWhitespace.capitalizeFirstOfEach}',
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
        ),
        3.height,
        Text(
          '${context.translation.partName}:  ${activity.activitySparePart?.partCatalogItem?.partName}',
          style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
        ),
        2.height,
        Text(
          '${context.translation.partNo}:  ${activity.activitySparePart?.partCatalogItem?.partNumber}',
          style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
        ),
        2.height,
        if (activity.activitySparePart?.comment?.isNotEmpty ?? false) ...[
          const Divider().defaultStyle(context),
          2.height,
          Text(
            activity.activitySparePart?.comment ?? "",
            style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
          ),
        ],
        if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[
          2.height,
          const Divider().defaultStyle(context),
          FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()),
        ],
      ],
    ).toShadowContainer(context, padding: 12, showShadow: false).onPress(() {
      if (showActionButtons) return;
      if (requestDetailProvider.isReadOnlyRequest) {
        editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
      } else if (userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId) {
        requestDetailProvider.isReadOnlyRequest = true;
        editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
      }
    });
  }

  Widget maintenanceActivityCard({required ServiceRequestDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) {
    double totalWorkingHours =
        activity.activityMaintenance?.activityMaintenanceTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endTime!).difference(DateTime.parse(item.startTime!)).inSeconds) ?? 0;

    bool showActionButtons = userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId &&
        userProvider.user!.type == UsersTypes.engineer &&
        requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 &&
        requestDetailProvider.currentWorkOrder?.data?.status?.value != 3;
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            //TODO will be here when fixed from backend..
            Row(
              children: [
                StatusLabel(
                  label: activity.activityStatus?.name,
                  textColor: AppColor.white10,
                  // textColor: AppColor.getHistoryLogStatusTextColorByName(activity.activityStatus!.name!),
                  // backgroundColor: AppColor.getHistoryLogStatusColorByName(activity.activityStatus!.name!),
                  backgroundColor: AppColor.primary10,
                ),
                5.width,
                StatusLabel(
                  label: activity.activityMaintenance?.activityType,
                  // textColor: AppColor.white10,
                  textColor: AppColor.getActivityTypeTextColor(activity.activityMaintenance?.activityType ?? ''),
                  backgroundColor: AppColor.getActivityTypeBgColor(activity.activityMaintenance?.activityType ?? ''),
                  // backgroundColor: AppColor.primary10,
                ),
              ],
            ),

            // "drag_icon".toSvgAsset(height: 12, width: 23, color: AppColor.neutral160),
            if (showActionButtons)
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  "edit_icon".toSvgAsset(height: 21, width: 21).onPress(() {
                    editMaintenanceRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
                  }),
                  24.width,
                  "delete_icon".toSvgAsset(height: 21, width: 21).onPress(() async {
                    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
                    int status = await requestDetailProvider.deleteActivityMaintenance(id: activity.id!, workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                    if (status == 200) {
                      await requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                      Navigator.pop(context);
                    } else {
                      Navigator.pop(context);
                    }
                  }),
                ],
              )
          ],
        ),
        6.height,
//activity type...
        Text(
          '${activity.activityType?.cleanupWhitespace.capitalizeFirstOfEach}',
          style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
        ),
        3.height,
        Text(
          '${context.translation.workingHours}:  ${totalWorkingHours > 0.0 ? ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round()) : '-'}',
          style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
        ),
        2.height,
        if (activity.activityMaintenance?.assistantEmployees != null && activity.activityMaintenance!.assistantEmployees!.isNotEmpty) ...[
          Text(
            '${context.translation.assistantEmployee}:  ${activity.activityMaintenance?.assistantEmployees?.first.user?.userName}',
            style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
          ),
        ] else ...[
          Text(
            '${context.translation.assignedEmployee}:  ${activity.activityMaintenance?.assignedEmployee?.userName}',
            style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
          ),
        ],

        2.height,
        if (activity.activityMaintenance?.technicalComment?.isNotEmpty ?? false) ...[
          const Divider().defaultStyle(context),
          2.height,
          Text(
            activity.activityMaintenance?.technicalComment ?? "",
            style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
          ),
        ],
        //need to add all info here...
        // if(requestDetailProvider.currentWorkOrder?.data?.status?.id==3498)...[
        //   const Divider().defaultStyle(context),
        //   2.height,
        //   // Text(
        //   //   activity.activityMaintenance?.technicalComment ?? "",
        //   //   style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
        //   // ),
        // ]
      ],
    ).toShadowContainer(context, padding: 12, showShadow: false).onPress(() {
      if (showActionButtons) return;
      if (requestDetailProvider.isReadOnlyRequest) {
        editMaintenanceRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
      } else if (userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId) {
        requestDetailProvider.isReadOnlyRequest = true;
        editMaintenanceRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity);
      }
    });
  }

  void editMaintenanceRequest({required BuildContext context, required ServiceRequestDetailProvider requestDetailProvider, required Activities activity}) async {
    // Map<String, dynamic> assistEmpData = {};
    try {
      // if (activity.activityMaintenance?.assistantEmployees != null && activity.activityMaintenance!.assistantEmployees!.isNotEmpty) {
      //   assistEmpData = {
      //     // 'id': activity.activityMaintenance?.assistantEmployees?[0].user?.userId != null ? num.tryParse(activity.activityMaintenance!.assistantEmployees![0].user!.userId!) : null,
      //     'id': null,
      //     'user': {
      //       'id': activity.activityMaintenance?.assistantEmployees?[0].user?.userId,
      //       // 'id': activity.activityMaintenance?.assistantEmployees?[0].user?.userId != null ? num.tryParse(activity.activityMaintenance!.assistantEmployees![0].user!.userId!) : null,
      //       'name': activity.activityMaintenance?.assistantEmployees?[0].user?.userName,
      //     },
      //   };
      // }

      requestDetailProvider.activityMaintenanceHelperModel = ActivityMaintenanceHelperModel(
        id: activity.id,
        workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId,
        startTime: activity.activityMaintenance?.startTime != null ? DateTime.parse(activity.activityMaintenance!.startTime!) : null,
        endTime: activity.activityMaintenance?.endTime != null ? DateTime.parse(activity.activityMaintenance!.endTime!) : null,
        activityStatus: activity.activityStatus,
        workingHour: activity.activityMaintenance?.workingHours ?? 0,
        travelHours: activity.activityMaintenance?.travelHours ?? 0,
        repairLocation: activity.activityMaintenance?.repairLocation,
        // lastSituation: activity.activityMaintenance?.lastSituation,
        assignedEmployee: activity.activityMaintenance?.assignedEmployee != null ? WorkOrderAssignedEmployee.fromJson(activity.activityMaintenance!.assignedEmployee!.toJson()) : null,
        technicalComment: activity.activityMaintenance?.technicalComment,
        assistantEmployList:activity.activityMaintenance!.assistantEmployees??[] ,
        // assistantEmployees:
        //     activity.activityMaintenance?.assistantEmployees != null && activity.activityMaintenance!.assistantEmployees!.isNotEmpty ? [AssistantEmployees.fromJson(assistEmpData)] : [],
        // modelAssistantEmployees:
        //     activity.activityMaintenance?.assistantEmployees != null && activity.activityMaintenance!.assistantEmployees!.isNotEmpty ? activity.activityMaintenance!.assistantEmployees![0] : null,
        supplierStartTime: activity.activityMaintenance?.supplierStartTime != null ? DateTime.parse(activity.activityMaintenance!.supplierStartTime!) : null,
        supplierEndTime: activity.activityMaintenance?.supplierEndTime != null ? DateTime.parse(activity.activityMaintenance!.supplierEndTime!) : null,
        supplierWorkingHour: activity.activityMaintenance?.supplierWorkingHours,
        activityMaintenanceTimers: activity.activityMaintenance?.activityMaintenanceTimers ?? [],
        supplier: activity.activityMaintenance?.supplier != null
            ? SupplierDetails(
                id: activity.activityMaintenance?.supplier?.id,
                suppliername: activity.activityMaintenance?.supplier?.name,
              )
            : null,
        supEngineer: activity.activityMaintenance?.supplier != null
            ? SuppEngineerWorkOrders(
                id: activity.activityMaintenance?.supplierEngineer?.id,
                personName: activity.activityMaintenance?.supplierEngineer?.name,
              )
            : null,
      );
      if (activity.activityMaintenance?.supplier != null) {
        requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons = await requestDetailProvider.getSupplierEngineerData(supplierName: activity.activityMaintenance!.supplier!.name!);
      }
      // requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
      // return;
    } catch (e) {
      print("Edit error $e");
    }
    Navigator.of(context).push(MaterialPageRoute(builder: (_) => MaintenanceRequestForm()));
  }

  void editSparePartRequest({required BuildContext context, required ServiceRequestDetailProvider requestDetailProvider, required Activities activity}) async {
    requestDetailProvider.sparePartHelperModel = SparePartHelperModel(
      id: activity.id,
      workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId,
      comment: activity.activitySparePart?.comment,
      sparePartAttachments: activity.activitySparePart?.acitiySparePartAttachments ?? [],
      activityStatus: activity.activityStatus,
      sparePart: SparePart(
          id: activity.activitySparePart?.partCatalogItem?.id,
          partName: activity.activitySparePart?.partCatalogItem?.partName,
          partNo: activity.activitySparePart?.partCatalogItem?.partNumber,
          oracleCode: activity.activitySparePart?.partCatalogItem?.oracleCode),
      quantity: activity.activitySparePart?.quantity,
      installQty: activity.activitySparePart?.installQty,
      returnQty: activity.activitySparePart?.returnQty,
      activityStatusId: activity.activityStatus?.id,
    );

    requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel);

    Navigator.of(context).push(MaterialPageRoute(
      builder: (_) => const SparePartRequest(),
    ));
  }
}

class ReorderWidget extends StatelessWidget {
  final Widget child;
  final Key key;

  const ReorderWidget({required this.key, required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      key: key,
      child: child,
    );
  }
}

class DummyClass extends StatelessWidget {
  const DummyClass({super.key});

  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}
