import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/ppm_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/helper/utils.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/device/model_definition.dart';
import 'package:test_sa/models/device/supplier.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/building.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/room_model.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/new_views/common_widgets/working_time_tile.dart';
import 'package:test_sa/providers/ppm_asset_availability_provider.dart';
import 'package:test_sa/providers/ppm_electrical_safety_provider.dart';
import 'package:test_sa/providers/ppm_service_provider.dart';
import 'package:test_sa/providers/ppm_task_status_provider.dart';
import 'package:test_sa/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.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/requests/request_status.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';
import 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.dart';

class WoInfoForm extends StatefulWidget {
  // final Ppm model;
  final PlanPreventiveVisit planPreventiveVisit;
  Function(Lookup)? onTypeOfServiceChange;

  WoInfoForm({Key? key, required this.planPreventiveVisit, this.onTypeOfServiceChange}) : super(key: key);

  @override
  State<WoInfoForm> createState() => _WoInfoFormState();
}

class _WoInfoFormState extends State<WoInfoForm> {
  List<TimerHistoryModel> timerList = [];
  double totalWorkingHours = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      PpmProvider ppmProvider = Provider.of<PpmProvider>(context, listen: false);
      calculateWorkingTime();
      if (widget.planPreventiveVisit.preventiveVisitAttachments != null && widget.planPreventiveVisit.preventiveVisitAttachments!.isNotEmpty) {
        ppmProvider.ppmPlanAttachments = [];
        ppmProvider.ppmPlanAttachments.addAll(widget.planPreventiveVisit.preventiveVisitAttachments!
            .whereType<GenericAttachmentModel>()
            .map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '', documentType: e.documentType))
            .toList());
      }
    });

    super.initState();
  }

  void calculateWorkingTime() {
    final helperModel = widget.planPreventiveVisit;
    final timers = helperModel.preventiveVisitTimers ?? [];
    totalWorkingHours = timers.fold<double>(0.0, (sum, item) {
      if (item.startDateTime == null || item.endDateTime == null) return sum;
      try {
        final start = DateTime.parse(item.startDateTime!);
        final end = DateTime.parse(item.endDateTime!);
        final diffInHours = end.difference(start).inSeconds / 3600.0; // convert to hours
        return sum + diffInHours;
      } catch (_) {
        return sum;
      }
    });
    timerList = timers.map((e) {
      return TimerHistoryModel(
        id: e.id,
        startTime: e.startDateTime,
        endTime: e.endDateTime,
        workingHours: e.workingHours,
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    // double totalWorkingHours =
    //     widget.planPreventiveVisit.preventiveVisitTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDateTime!).difference(DateTime.parse(item.startDateTime!)).inSeconds) ?? 0;

    return Consumer<PpmProvider>(builder: (context, ppmProvider, child) {
      return ListView(
        padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 16),
        children: [
          IgnorePointer(
            ignoring: ppmProvider.isReadOnly,
            child: Column(
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (widget.planPreventiveVisit.visitStatus != null)
                      StatusLabel(
                        label: widget.planPreventiveVisit.visitStatus?.name,
                        textColor: AppColor.getRequestStatusTextColorByName(context, widget.planPreventiveVisit.visitStatus?.name),
                        backgroundColor: AppColor.getRequestStatusColorByName(context, widget.planPreventiveVisit.visitStatus?.name),
                      ),
                    InfoHeader16Widget(widget.planPreventiveVisit.planName!),
                    // widget.planPreventiveVisit.planName!.bodyText(context).custom(color: AppColor.headingTextColor(context)),
                    InfoTextWidget(
                      label: context.translation.pmPlanNo,
                      value: widget.planPreventiveVisit.planNo,
                    ),
                    InfoTextWidget(
                      label: 'Work Order Number'.addTranslation,
                      value: widget.planPreventiveVisit.visitNo,
                    ),
                    InfoTextWidget(label: context.translation.creationDate, value: widget.planPreventiveVisit.creationDate?.toMonthYearFormat),
                    InfoTextWidget(label: context.translation.closedDate, value: widget.planPreventiveVisit.closedDate != null ? widget.planPreventiveVisit.closedDate?.toMonthYearFormat : '-'),
                    InfoTextWidget(label: context.translation.nextPmDate, value: widget.planPreventiveVisit.nextPMDate != null ? widget.planPreventiveVisit.nextPMDate!.toMonthYearFormat : '-'),
                    InfoTextWidget(label: context.translation.assignEngineer, value: widget.planPreventiveVisit.assignedEmployee?.userName),
                    InfoTextWidget(label: context.translation.executionTimeFrame, value: '${widget.planPreventiveVisit.executionTimeFrame ?? ""} days'),
                    // '${context.translation.pmPlanNo}:  ${widget.planPreventiveVisit.planNo}'.bodyText2(context).custom(color: AppColor.neutral120),
                    //need to add in translation it's suggestion from ahmed..
                    // 'Work Order Number:  ${widget.planPreventiveVisit.visitNo}'.bodyText2(context).custom(color: AppColor.neutral120),
                    // '${context.translation.creationDate}:  ${widget.planPreventiveVisit.creationDate?.toMonthYearFormat}'.bodyText2(context).custom(color: AppColor.neutral120),
                    // '${context.translation.closedDate}:  ${widget.planPreventiveVisit.closedDate != null ? widget.planPreventiveVisit.closedDate?.toMonthYearFormat : '-'}'
                    //     .bodyText2(context)
                    //     .custom(color: AppColor.neutral120),

                    // '${context.translation.nextPmDate}:  ${widget.planPreventiveVisit.nextPMDate != null ? widget.planPreventiveVisit.nextPMDate!.toMonthYearFormat : '-'}'
                    //     .bodyText2(context)
                    //     .custom(color: AppColor.neutral120),
                    // '${context.translation.assignEngineer}:  ${widget.planPreventiveVisit.assignedEmployee?.userName ?? ""}'.bodyText2(context).custom(color: AppColor.neutral120),
                    // '${context.translation.executionTimeFrame}:  ${widget.planPreventiveVisit.executionTimeFrame ?? ""} days'.bodyText2(context).custom(color: AppColor.neutral120),
                  ],
                ).toShadowContainer(context),
                12.height,
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        InfoHeader16Widget(widget.planPreventiveVisit.assetName ?? '').expanded,
                        // widget.planPreventiveVisit.assetName!.bodyText(context).custom(color: AppColor.headingTextColor(context)).expanded,
                        const Icon(Icons.open_in_new_rounded, color: AppColor.primary10, size: 20).onPress(() {
                          Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: widget.planPreventiveVisit.asset!.id);
                        }),
                      ],
                    ),
                    // 2.height,
                    InfoTextWidget(
                      label: context.translation.assetNo,
                      value: widget.planPreventiveVisit.asset?.assetNumber,
                    ),
                    InfoTextWidget(
                      label: context.translation.model,
                      value: widget.planPreventiveVisit.model,
                    ),
                    // '${context.translation.assetNo}:  ${widget.planPreventiveVisit.asset?.assetNumber}'.bodyText2(context).custom(color: AppColor.lightTextColor(context)),
                    // '${context.translation.model}:  ${widget.planPreventiveVisit.model}'.bodyText2(context).custom(color: AppColor.lightTextColor(context)),
                  ],
                ).toShadowContainer(context),

                // SingleItemDropDownMenu<Lookup, PPMVisitStatusProvider>(
                //   context: context,
                //   initialValue:
                //       widget.planPreventiveVisit.visitStatus?.id == null ? null : Lookup(name: widget.planPreventiveVisit.visitStatus?.name ?? "", id: widget.planPreventiveVisit.visitStatus?.id?.toInt()),
                //   title: context.translation.ppmVisit,
                //   onSelect: (value) {
                //     if (value?.value == 4) {
                //       "Status cannot be change to ${value?.name}.".addTranslation.showToast;
                //       setState(() {});
                //       return;
                //     }
                //
                //     if (value != null) {
                //       widget.planPreventiveVisit.visitStatus?.name = value.name;
                //       widget.planPreventiveVisit.visitStatus?.id = value.id;
                //     }
                //   },
                // ),

                // SingleItemDropDownMenu<Lookup, PPMDeviceStatusProvider>(
                //   context: context,
                //   initialValue: widget.planPreventiveVisit.deviceStatusId == null ? null : Lookup(name: widget.model.deviceStatusName ?? "", id: widget.model.deviceStatusId?.toInt()),
                //   title: context.translation.deviceStatus,
                //   onSelect: (value) {
                //     if (value != null) {
                //       widget.planPreventiveVisit.deviceStatusId = value.id;
                //       widget.planPreventiveVisit.deviceStatusName = value.name;
                //     }
                //   },
                // ),
                8.height,
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SingleItemDropDownMenu<Lookup, PpmTaskStatusProvider>(
                      context: context,
                      showShadow: false,
                      initialValue:
                          widget.planPreventiveVisit.taskStatus == null ? null : Lookup(name: widget.planPreventiveVisit.taskStatus?.name ?? "", id: widget.planPreventiveVisit.taskStatus?.id),
                      title: context.translation.pmTestResult,
                      // backgroundColor: AppColor.fieldBgColor(context),
                      onSelect: (value) {
                        if (value != null) {
                          widget.planPreventiveVisit.taskStatus = value;
                        }
                      },
                    ),
                    8.height,
                    ADatePicker(
                      label: context.translation.actualVisit,
                      hideShadow: true,
                      backgroundColor: AppColor.fieldBgColor(context),
                      date: widget.planPreventiveVisit.acutalDateOfVisit,
                      from: DateTime.tryParse(widget.planPreventiveVisit.creationDate ?? ''),
                      formatDateWithTime: true,
                      onDatePicker: (selectedDate) {
                        showThemedTimePicker(
                          context: context,
                          initialTime: TimeOfDay.now(),
                        ).then((selectedTime) {
                          if (selectedTime != null) {
                            // final TimeOfDay now = TimeOfDay.now();
                            // final bool isBeforeNow = Utils.isBeforeOrEqualCurrentTime(selectedTime, now);
                            // if (!isBeforeNow) {
                            //   "Please select a time before the current time.".showToast;
                            //   return;
                            // }

                            DateTime selectedDateTime = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
                            if (selectedDateTime.isAfter(DateTime.now())) {
                              "Start time is after than current time".showToast;
                              selectedTime = null;
                              return;
                            }
                            setState(() {
                              widget.planPreventiveVisit.acutalDateOfVisit = selectedDateTime;
                            });
                          }
                        });
                      },
                    ),
                    // SingleItemDropDownMenu<Lookup, PpmElectricalSafetyProvider>(
                    //   context: context,
                    //   backgroundColor: AppColor.neutral100,
                    //   initialValue: widget.planPreventiveVisit.safety?.id == null ? null : Lookup(name: widget.planPreventiveVisit.safety?.name ?? "", id: widget.planPreventiveVisit.safety?.id),
                    //   title: context.translation.actualVisit,
                    //   onSelect: (value) {
                    //     if (value != null) {
                    //       widget.planPreventiveVisit.safety = value;
                    //       // widget.planPreventiveVisit.safety?.id = value.id;
                    //       // widget.planPreventiveVisit.safety?.name = value.name;
                    //     }
                    //   },
                    // ),

                    8.height,
                    SingleItemDropDownMenu<Lookup, PpmElectricalSafetyProvider>(
                      context: context,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showShadow: false,
                      initialValue: widget.planPreventiveVisit.safety?.id == null ? null : Lookup(name: widget.planPreventiveVisit.safety?.name ?? "", id: widget.planPreventiveVisit.safety?.id),
                      title: "Electrical Safety",
                      onSelect: (value) {
                        if (value != null) {
                          widget.planPreventiveVisit.safety = value;
                        }
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Lookup, PpmAssetAvailabilityProvider>(
                      context: context,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showShadow: false,
                      initialValue: widget.planPreventiveVisit.assetAvailability == null
                          ? null
                          : Lookup(name: widget.planPreventiveVisit.assetAvailability?.name ?? "", id: widget.planPreventiveVisit.assetAvailability?.id),
                      title: "Asset Availability",
                      onSelect: (value) {
                        if (value != null) {
                          widget.planPreventiveVisit.assetAvailability = value;
                        }
                      },
                    ),
                    8.height,
                    SingleItemDropDownMenu<Lookup, PpmServiceProvider>(
                      context: context,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showShadow: false,
                      initialValue: widget.planPreventiveVisit.typeOfService == null
                          ? null
                          : Lookup(name: widget.planPreventiveVisit.typeOfService?.name ?? "", id: widget.planPreventiveVisit.typeOfService?.id?.toInt()),
                      title: context.translation.typeOfPm,
                      onSelect: (value) {
                        if (value != null) {
                          widget.planPreventiveVisit.typeOfService = value;
                          if (widget.planPreventiveVisit.typeOfService?.value == 2) {
                            ppmProvider.totalTabs = 4;
                          } else {
                            ppmProvider.totalTabs = 3;
                          }
                          widget.onTypeOfServiceChange!(value);
                        }
                      },
                    ),
                    8.height,
                    _timerWidget(context, totalWorkingHours),
                    8.height,
                    AppTextFormField(
                      labelText: context.translation.comment,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showShadow: false,
                      initialValue: (widget.planPreventiveVisit.comments ?? "").toString(),
                      textAlign: TextAlign.center,
                      style: Theme.of(context).textTheme.titleMedium,
                      onChange: (value) {
                        widget.planPreventiveVisit.comments = value;
                      },
                    ),
                    16.height,
                    AttachmentPicker(
                      label: context.translation.attachments,
                      showAsListView: true,
                      attachment: ppmProvider.ppmPlanAttachments,
                      buttonColor: AppColor.black10,
                      onlyImages: false,
                      buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                    ),
                  ],
                ).toShadowContainer(context),
              ],
            ),
          ),
          //TODO need to check this also...
          // ESignature(
          //   title: context.translation.nurseSignature,
          //   oldSignature: widget.planPreventiveVisit.nurseSignature,
          //   newSignature: widget.planPreventiveVisit.localNurseSignature,
          //   onChange: (signature) {
          //     widget.planPreventiveVisit.localNurseSignature = signature;
          //     widget.planPreventiveVisit.nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
          //   },
          // ),
          // ESignature(
          //   title: context.translation.engSign,
          //   oldSignature: widget.planPreventiveVisit.engSignature,
          //   newSignature: widget.planPreventiveVisit.localEngineerSignature,
          //   onChange: (signature) {
          //     widget.planPreventiveVisit.localEngineerSignature = signature;
          //     widget.planPreventiveVisit.engSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
          //   },
          // ),
        ],
      );
    });
  }

  _buildAssetDetailBottomSheet(BuildContext context) {
    PlanPreventiveVisit model = widget.planPreventiveVisit;
    Asset asset = Asset(
      id: model.asset?.id,
      assetSerialNo: model.asset?.assetSerialNo,
      assetNumber: model.asset?.assetNumber,
      building: Building(name: model.buildingName),
      floor: Floor(name: model.floorName),
      site: Site(custName: model.siteName),
      supplier: Supplier(suppliername: model.supplierName),
      modelDefinition: ModelDefinition(modelName: model.model, manufacturerName: model.manufacturer, assetName: model.assetName),
      room: Rooms(value: int.tryParse(model.roomName ?? '')),
      department: Department(departmentName: model.departmentName),
    );
    return AssetDetailBottomSheet(asset).bottomSheetContainer(context);
  }

  // Future<Asset> getAssetById () async {
  //   Asset asset = Asset();
  //   AssetProvider _assetProvider = Provider.of<AssetProvider>(context, listen: false);
  //   if(widget.planPreventiveVisit.asset!=null){
  //     AssetByIdModel ?assetByIdModel  = await   _assetProvider.getAssetById(widget.planPreventiveVisit.asset!.id!.toInt(), context.translation);
  //     asss
  //   }
  //   return asset;
  // }

  Widget _timerWidget(BuildContext context, double totalWorkingHours) {
    return Column(
      children: [
        AppTimer(
          label: context.translation.workingHours,
          // decoration: BoxDecoration(color: AppColor.fieldBgColor(context), borderRadius: BorderRadius.circular(10)),
          width: double.infinity,
          timer: widget.planPreventiveVisit.tbsTimer,
          pickerTimer: widget.planPreventiveVisit.ppMTimePicker,
          pickerFromDate: DateTime.tryParse(widget.planPreventiveVisit.createdDate ?? ''),
          onPick: (time) {
            widget.planPreventiveVisit.ppMTimePicker = time;
          },
          timerProgress: (isRunning) {},
          onChange: (timer) async {
            widget.planPreventiveVisit.tbsTimer = timer;
            if (timer.startAt != null && timer.endAt != null) {
              widget.planPreventiveVisit.timerModelList = widget.planPreventiveVisit.timerModelList ?? [];
              widget.planPreventiveVisit.timerModelList!.add(timer);
            }
            return true;
          },
        ),
        11.height,
        if (totalWorkingHours > 0.0) ...[
          WorkingTimeTile(
            timerList: timerList,
            totalWorkingTime: totalWorkingHours,
          ),
          // Row(
          //   crossAxisAlignment: CrossAxisAlignment.center,
          //   mainAxisAlignment: MainAxisAlignment.start,
          //   children: [
          //     context.translation.totalWorkingTime.bodyText2(context),
          //     " ${ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round())}".bodyText(context).custom(color: AppColor.black20),
          //   ],
          // ),
        ],
        // 8.height,
      ],
    );
  }

// String formatDuration1(int seconds) {
//   int hours = seconds ~/ 3600;
//   int minutes = (seconds % 3600) ~/ 60;
//
//   String formattedDuration = '';
//   if (hours > 0) {
//     formattedDuration += '$hours hour${hours > 1 ? 's' : ''} ';
//   }
//   if (minutes > 0) {
//     formattedDuration += '$minutes minute${minutes > 1 ? 's' : ''} ';
//   }
//   if (formattedDuration.isEmpty) {
//     formattedDuration = 'Less than a minute';
//   }
//
//   return formattedDuration.trim();
// }
//
// String formatDuration(int seconds) {
//   int hours = seconds ~/ 3600;
//   int minutes = (seconds % 3600) ~/ 60;
//   int remainingSeconds = seconds % 60;
//
//   String formattedDuration = '';
//   if (hours > 0) {
//     formattedDuration += '$hours hour${hours > 1 ? 's' : ''} ';
//   }
//   if (minutes > 0) {
//     formattedDuration += '$minutes minute${minutes > 1 ? 's' : ''} ';
//   }
//   if (remainingSeconds > 0) {
//     formattedDuration += '$remainingSeconds second${remainingSeconds > 1 ? 's' : ''} ';
//   }
//   if (formattedDuration.isEmpty) {
//     formattedDuration = 'Less than a second';
//   }
//
//   return formattedDuration.trim();
// }
}
