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/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/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/service_request_latest/request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/service_request_latest/views/components/bottom_sheets/service_request_bottomsheet.dart';
import 'package:test_sa/service_request_latest/views/forms/maintenance_request/maintenance_request_main.dart';
import 'package:test_sa/service_request_latest/views/forms/spare_part/spare_part_request.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';

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> {
  bool showReorderView = false;

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

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

  List<Activities> reOrderActivities = [];

  List<Activities> activities = [];

  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
      appBar: DefaultAppBar(
        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<RequestDetailProvider>(builder: (context, RequestDetailProvider requestDetailProvider, child) {
        if (showReorderView && reOrderActivities.isEmpty) {
          reOrderActivities = requestDetailProvider.currentWorkOrder!.data!.activities;
        } else {
          activities = requestDetailProvider.currentWorkOrder!.data!.activities;
        }

        return Column(
          children: [
            (activities.isEmpty && reOrderActivities.isEmpty)
                ? NoDataFound(message: context.translation.noDataFound).expanded
                : showReorderView
                    ? ReorderableListView(
                        padding: const EdgeInsets.all(16),
                        children: [
                          for (int index = 0; index < reOrderActivities.length; index++)
                            if (reOrderActivities[index].activityMaintenance != null)
                              ReorderWidget(
                                key: ValueKey(index),
                                child: maintenanceActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: reOrderActivities[index])
                                    .paddingOnly(top: 8, bottom: 8),
                              )
                            else
                              ReorderWidget(
                                key: ValueKey(index),
                                child: sparePartActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: reOrderActivities[index])
                                    .paddingOnly(top: 8, bottom: 8),
                              )
                        ],
                        onReorder: (oldIndex, newIndex) {
                          setState(() {
                            if (oldIndex < newIndex) {
                              newIndex -= 1;
                            }
                            final Activities item = reOrderActivities.removeAt(oldIndex);
                            reOrderActivities.insert(newIndex, item);
                          });
                        }).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])
                                .paddingOnly(top: 8, bottom: 8);
                          }
                          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(
                  child: AppFilledButton(
                label: showReorderView ? "Confirm Order".addTranslation : context.translation.createNewActivity,
                maxWidth: true,
                buttonColor: AppColor.primary10,
                loading: requestDetailProvider.isLoading,
                onPressed: () async {
                  if (showReorderView) {
                    //  requestDetailProvider.currentWorkOrder!.data!.activities = reOrderActivities;
                    List<Map<String, dynamic>> data = [];
                    for (int i = 0; i < reOrderActivities.length; i++) {
                      data.add({"id": reOrderActivities[i].id, "orderNo": i});
                    }
                    reOrderActivities = [];
                    requestDetailProvider.reOrderActivities(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, reOrderActivityDTOs: data);
                    showReorderView = false;
                    return;
                  }
                  ServiceRequestBottomSheet.activityTypeBottomSheet(context: context);
                },
              ))
          ],
        );
      }),
    );
  }

  Widget sparePartActivityCard({required RequestDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            StatusLabel(
              label: activity.activityStatus?.name,
              textColor: AppColor.getHistoryLogStatusTextColorByName(activity.activityStatus!.name!),
              backgroundColor: AppColor.getHistoryLogStatusColorByName(activity.activityStatus!.name!),
            ),
            "drag_icon".toSvgAsset(height: 12, width: 23, color: AppColor.neutral160),
            if (userProvider.user!.type == UsersTypes.engineer && requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && requestDetailProvider.currentWorkOrder?.data?.status?.value != 3)
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  "edit_icon".toSvgAsset(height: 21, width: 21).onPress(() {
                    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,
                      activityStatusId: activity.activityStatus?.id,
                    );

                    requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel);

                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (_) => const SparePartRequest(),
                    ));
                  }),
                  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,
//TODO description text not in api.
// Text(
//   '${context.translation.date}:  ${activity.currentSituation?.date}',
//   style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
// ),
        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(() {
//TODO write onview detail method..
// Navigator.push(
//   context,
//   MaterialPageRoute(builder: (context) => WorkOrderDetailsPage(workOrder: activity, serviceRequest: ServiceRequest())),
// );
    });
  }

  Widget maintenanceActivityCard({required RequestDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            StatusLabel(
              label: activity.activityStatus?.name,
              textColor: AppColor.getHistoryLogStatusTextColorByName(activity.activityStatus!.name!),
              backgroundColor: AppColor.getHistoryLogStatusColorByName(activity.activityStatus!.name!),
            ),
            "drag_icon".toSvgAsset(height: 12, width: 23, color: AppColor.neutral160),
            if (userProvider.user!.type == UsersTypes.engineer && requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && requestDetailProvider.currentWorkOrder?.data?.status?.value != 3)
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  "edit_icon".toSvgAsset(height: 21, width: 21).onPress(() {
                    onEditMaintenanceRequestPress(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.callLastSituation}:  ${activity.activityMaintenance?.lastSituation?.name}',
          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,
//TODO description text not in api.
// Text(
//   '${context.translation.date}:  ${activity.currentSituation?.date}',
//   style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
// ),
        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(() {
//TODO write onview detail method..
// Navigator.push(
//   context,
//   MaterialPageRoute(builder: (context) => WorkOrderDetailsPage(workOrder: activity, serviceRequest: ServiceRequest())),
// );
    });
  }

  void onEditMaintenanceRequestPress({required BuildContext context, required RequestDetailProvider 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,
        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,
        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: (_) => const MaintenanceRequestForm(),
    ));
  }
}

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,
    );
  }
}
