import 'package:flutter/material.dart';
import 'package:provider/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/service_request/service_report.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/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/work_order/vendor_provider.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/pages/user/requests/add_supplier_engineer_bottom_sheet.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import '../../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../../new_views/common_widgets/single_item_drop_down_menu.dart';

class ExternalMaintenanceRequest extends StatefulWidget {
  static const String id = "/add-external-activity";

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

  @override
  _ExternalMaintenanceRequestState createState() => _ExternalMaintenanceRequestState();
}

class _ExternalMaintenanceRequestState extends State<ExternalMaintenanceRequest> with TickerProviderStateMixin {
  ServiceReport? _serviceReport;
  final TextEditingController _workingHoursController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

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

  void getInitialData() {
    ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    _workingHoursController.text =
        requestDetailProvider.activityMaintenanceHelperModel?.supplierWorkingHour != null ? requestDetailProvider.activityMaintenanceHelperModel!.supplierWorkingHour.toString() : '';
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ServiceRequestDetailProvider>(builder: (context, ServiceRequestDetailProvider requestDetailProvider, child) {
      return IgnorePointer(
        ignoring: requestDetailProvider.isReadOnlyRequest,
        child: Column(
          children: [
            Form(
              key: _formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SingleItemDropDownMenu<SupplierDetails, VendorProvider>(
                    context: context,
                    title: context.translation.supplier,
                    backgroundColor: AppColor.neutral100,
                    initialValue: requestDetailProvider.activityMaintenanceHelperModel?.supplier,
                    showAsBottomSheet: true,
                    onSelect: (supplier) {
                      if (supplier != null) {
                        requestDetailProvider.activityMaintenanceHelperModel?.supplier = supplier;
                        //    _subWorkOrders.supplier = supplier;
                        //   log(_subWorkOrders.supplier?.suppPersons?.map((e) => e.personName)?.toString());
                        setState(() {});
                      }
                    },
                  ),
                  8.height,
                  Row(
                    children: [
                      SingleItemDropDownMenu<SuppPersons, NullableLoadingProvider>(
                        context: context,
                        backgroundColor: requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppliername == null ? AppColor.neutral40 : AppColor.neutral100,
                        title: context.translation.supplierEngineer,
                        enabled: requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons?.isNotEmpty ?? false,
                        staticData: requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons,
                        showAsBottomSheet: true,
                        initialValue: requestDetailProvider.activityMaintenanceHelperModel?.supEngineer == null
                            ? null
                            : SuppPersons.fromJson(requestDetailProvider.activityMaintenanceHelperModel?.supEngineer?.toJson()),
                        onSelect: (suppPerson) {
                          print(suppPerson?.toJson());
                          if (suppPerson != null) {
                            requestDetailProvider.activityMaintenanceHelperModel?.supEngineer = SuppEngineerWorkOrders.fromJson(suppPerson.toJson());
                            requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                            // engineer = SuppEngineerWorkOrders(
                            //   id: suppPerson?.supplierId,
                            //   supplierContactId: suppPerson?.id,
                            //   personName: suppPerson?.personName,
                            //   contact: suppPerson?.contact,
                            //   externalEngCode: suppPerson?.externalEngCode,
                            //   email: suppPerson?.email,
                            // );
                            setState(() {});
                          }
                        },
                      ).expanded,
                      8.width,
                      Container(
                        height: 56.toScreenHeight,
                        width: 60.toScreenWidth,
                        decoration: BoxDecoration(
                          color: requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppliername == null ? AppColor.neutral40 : AppColor.neutral100,
                          borderRadius: BorderRadius.circular(10),
                          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
                        ),
                        child: Icon(
                          Icons.add,
                          color: context.isDark ? null : AppColor.neutral60,
                        ),
                      ).onPress(requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppliername == null
                          ? null
                          : () async {
                              SuppEngineerWorkOrders suppEngineer = (await showModalBottomSheet(
                                context: context,
                                useSafeArea: true,
                                isScrollControlled: true,
                                backgroundColor: Colors.transparent,
                                builder: (context) => AddSupplierEngineerBottomSheet(requestDetailProvider.activityMaintenanceHelperModel!.supplier!.id!.toInt()),
                              )) as SuppEngineerWorkOrders;
                              requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons ??= [];
                              requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons?.add(SuppPersons.fromJson(suppEngineer.toJson()));
                              requestDetailProvider.activityMaintenanceHelperModel?.supEngineer = suppEngineer;
                              setState(() {});
                            }),
                    ],
                  ),
                  8.height,
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ADatePicker(
                        label: context.translation.startTime,
                        hideShadow: true,
                        backgroundColor: AppColor.neutral100,
                        date: requestDetailProvider.activityMaintenanceHelperModel?.supplierStartTime,
                        formatDateWithTime: true,
                        onDatePicker: (selectedDate) {
                          showTimePicker(
                            context: context,
                            initialTime: TimeOfDay.now(),
                          ).then((selectedTime) {
                            // Handle the selected date and time here.
                            if (selectedTime != null) {
                              DateTime selectedDateTime = DateTime(
                                selectedDate.year,
                                selectedDate.month,
                                selectedDate.day,
                                selectedTime.hour,
                                selectedTime.minute,
                              );
                              requestDetailProvider.activityMaintenanceHelperModel?.supplierStartTime = selectedDateTime;
                              requestDetailProvider.activityMaintenanceHelperModel?.supplierEndTime = null;
                              requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                              _workingHoursController.clear();
                              ServiceRequestUtils.calculateAndAssignWorkingHours(
                                startTime: requestDetailProvider.activityMaintenanceHelperModel!.supplierStartTime,
                                endTime: requestDetailProvider.activityMaintenanceHelperModel!.endTime,
                                workingHoursController: _workingHoursController,
                                updateModel: (hours) {
                                  requestDetailProvider.activityMaintenanceHelperModel?.supplierWorkingHour = hours;
                                },
                              );
                            }
                          });
                        },
                      ).expanded,
                      8.width,
                      ADatePicker(
                        label: context.translation.endTime,
                        hideShadow: true,
                        backgroundColor: AppColor.neutral100,
                        date: requestDetailProvider.activityMaintenanceHelperModel?.supplierEndTime,
                        formatDateWithTime: true,
                        onDatePicker: (selectedDate) {
                          showTimePicker(
                            context: context,
                            initialTime: TimeOfDay.now(),
                          ).then((selectedTime) {
                            // Handle the selected date and time here.
                            if (selectedTime != null) {
                              DateTime selectedDateTime = DateTime(
                                selectedDate.year,
                                selectedDate.month,
                                selectedDate.day,
                                selectedTime.hour,
                                selectedTime.minute,
                              );
                              if (requestDetailProvider.activityMaintenanceHelperModel!.supplierStartTime != null &&
                                  selectedDateTime.isBefore(requestDetailProvider.activityMaintenanceHelperModel!.supplierStartTime!)) {
                                "End Date time must be greater then start date".showToast;
                                return;
                              }
                              requestDetailProvider.activityMaintenanceHelperModel?.supplierEndTime = selectedDateTime;
                              requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                              ServiceRequestUtils.calculateAndAssignWorkingHours(
                                startTime: requestDetailProvider.activityMaintenanceHelperModel!.supplierStartTime,
                                endTime: requestDetailProvider.activityMaintenanceHelperModel!.supplierEndTime,
                                workingHoursController: _workingHoursController,
                                updateModel: (hours) {
                                  requestDetailProvider.activityMaintenanceHelperModel?.supplierWorkingHour = hours;
                                },
                              );
                            }
                          });
                        },
                      ).expanded,
                    ],
                  ),
                  8.height,
                  AppTextFormField(
                    labelText: context.translation.workingHours,
                    backgroundColor: AppColor.neutral80,
                    controller: _workingHoursController,
                    suffixIcon: "clock".toSvgAsset(width: 20, color: context.isDark ? AppColor.neutral10 : null).paddingOnly(end: 16),
                    initialValue:
                        requestDetailProvider.activityMaintenanceHelperModel?.supplierWorkingHour != null ? requestDetailProvider.activityMaintenanceHelperModel?.supplierWorkingHour.toString() : '',
                    textAlign: TextAlign.center,
                    labelStyle: AppTextStyles.textFieldLabelStyle,
                    enable: false,
                    showShadow: false,
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                  8.height,
                ],
              ),
            ).toShadowContainer(context).paddingOnly(start: 16, end: 16, top: 12),
          ],
        ),
      );
    });
  }
}
