import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_provider.dart';
import 'package:test_sa/controllers/validator/validator.dart';
import 'package:test_sa/dashboard_latest/dashboard_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/enums/user_types.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/floor.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/models/new_models/task_request/task_type_model.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.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/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/demo_module/provider/demo_period_lookup_provider.dart';
import 'package:test_sa/modules/demo_module/provider/demo_provider.dart';
import 'package:test_sa/modules/loan_module/models/loan_form_model.dart';
import 'package:test_sa/modules/loan_module/models/medical_department_model.dart';
import 'package:test_sa/modules/loan_module/provider/loan_period_provider.dart';
import 'package:test_sa/modules/loan_module/provider/loan_provider.dart';
import 'package:test_sa/modules/loan_module/provider/loan_provider.dart';
import 'package:test_sa/modules/loan_module/provider/medical_department_provider.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_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/department_provider.dart';
import 'package:test_sa/providers/gas_request_providers/site_provider.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/work_order/vendor_provider.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 '../../../../../../new_views/common_widgets/default_app_bar.dart';
import '../../models/new_models/department.dart';
import 'demo_detail_view_page.dart';
import 'demo_document_lookup_provider.dart';
import 'models/demo_form_model.dart';

class CreateDemoRequestPage extends StatefulWidget {
  static const String id = "/create-demo-request";

  CreateDemoRequestPage({Key? key}) : super(key: key);

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

class _CreateDemoRequestPageState extends State<CreateDemoRequestPage> with TickerProviderStateMixin {
  List<GenericAttachmentModel> _attachments = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final DemoFormModel _demoFormModel = DemoFormModel(id: 0);
  TextEditingController vendorEmailController = TextEditingController();
  TextEditingController vendorPhoneController = TextEditingController();

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

  Lookup? demoDocumentLookup;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'Demo Request'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                spacing: 12,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ...siteSection(),
                  ...doctorInfoSection(),
                  ...assetSection(),
                  ...vendorDetailsSection(),
                  ...attachmentSection(),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Checkbox(
                          value: _demoFormModel.demoEaluationAcknowledge,
                          activeColor: AppColor.primary10,
                          side: BorderSide(color: AppColor.loadingColor(context), width: 1.0),
                          visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          onChanged: (value) {
                            setState(() {
                              _demoFormModel.demoEaluationAcknowledge = value!;
                            });
                          }),
                      8.width,
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        spacing: 4,
                        children: [
                          InfoTextLabelWidget(
                            label: "DEMO outcome evaluation form acknowledgement",
                            textStyle: AppTextStyles.bodyText,
                            color: AppColor.textColor(context),
                          ),
                          InfoTextLabelWidget(
                            label: "I acknowledge at the end of the trial period I will complete and submit the Medical Technology Trial Outcome Form within two weeks.",
                            color: AppColor.lightTextColor(context),
                          ),
                        ],
                      ).expanded,
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Checkbox(
                          value: _demoFormModel.acknowledgeNotEquipment,
                          activeColor: AppColor.primary10,
                          side: BorderSide(color: AppColor.loadingColor(context), width: 1.0),
                          visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          onChanged: (value) {
                            setState(() {
                              _demoFormModel.acknowledgeNotEquipment = value!;
                            });
                          }),
                      8.width,
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        spacing: 4,
                        children: [
                          InfoTextLabelWidget(
                            label: "Acknowledgement of not using the equipment",
                            textStyle: AppTextStyles.bodyText,
                            color: AppColor.textColor(context),
                          ),
                          InfoTextLabelWidget(
                            label: "I acknowledge at the end of the trial period I will not use the DEMO medical equipment & I will not book any patient on the DEMO medical equipment.",
                            color: AppColor.lightTextColor(context),
                          ),
                        ],
                      ).expanded,
                    ],
                  ),
                ],
              ).toShadowContainer(context),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                disableButton: !_demoFormModel.demoEaluationAcknowledge || !_demoFormModel.acknowledgeNotEquipment,
                label: context.translation.submitRequest,
                onPressed: _submit,
                // buttonColor: AppColor.primary10,
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> siteSection() {
    return [
      InfoHeader16Widget('Site Details'.addTranslation),
      SingleItemDropDownMenu<Site, SiteProvider>(
        context: context,
        title: context.translation.site,
        initialValue: _demoFormModel.site,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Please select a site";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          _demoFormModel.site = value;
          _demoFormModel.building = null;
          _demoFormModel.floor = null;
          _demoFormModel.department = null;
          setState(() {});
        },
      ),
      SingleItemDropDownMenu<Building, NullableLoadingProvider>(
        context: context,
        title: context.translation.building,
        initialValue: _demoFormModel.building,
        showShadow: false,
        showAsBottomSheet: true,
        validator: (value) {
          if (value == null) return "Please select a building";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _demoFormModel.site?.buildings?.isNotEmpty ?? false,
        staticData: _demoFormModel.site?.buildings ?? [],
        onSelect: (value) {
          _demoFormModel.building = value;
          _demoFormModel.floor = null;
          _demoFormModel.department = null;
          setState(() {});
        },
      ),
      SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
        context: context,
        title: context.translation.floor,
        showShadow: false,
        showAsBottomSheet: true,
        initialValue: _demoFormModel.floor,
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _demoFormModel.building?.floors?.isNotEmpty ?? false,
        staticData: _demoFormModel.building?.floors ?? [],
        validator: (value) {
          if (value == null) return "Please select a floor";
          return null;
        },
        onSelect: (value) {
          _demoFormModel.floor = value;
          _demoFormModel.department = null;
          setState(() {});
        },
      ),
      SingleItemDropDownMenu<Department, NullableLoadingProvider>(
        context: context,
        title: context.translation.department,
        showShadow: false,
        showAsBottomSheet: true,
        initialValue: _demoFormModel.department,
        backgroundColor: AppColor.fieldBgColor(context),
        enabled: _demoFormModel.floor?.departments?.isNotEmpty ?? false,
        validator: (value) {
          if (value == null) return "Please select a department";
          return null;
        },
        staticData: _demoFormModel.floor?.departments ?? [],
        onSelect: (value) {
          _demoFormModel.department = value;
          _demoFormModel.room = null;
          setState(() {});
        },
      ),
    ];
  }

  List<Widget> doctorInfoSection() {
    return [
      InfoHeader16Widget('Doctor Details'.addTranslation),
      AppTextFormField(
        initialValue: "",
        labelText: "Name",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        onChange: (value) {
          _demoFormModel.docName = value;
        },
      ),
      AppTextFormField(
        initialValue: "",
        labelText: "Contact Number",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.phone,
        onChange: (value) {
          _demoFormModel.docNumber = value;
        },
      ),
      AppTextFormField(
        initialValue: "",
        labelText: "Email",
        validator: (value) {
          if ((value ?? "").isEmpty) {
            return "Mandatory";
          } else {
            return Validator.isEmail(value!) ? null : context.translation.emailValidateMessage;
          }
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.emailAddress,
        onChange: (value) {
          _demoFormModel.docEmail = value;
        },
      ),
      AppTextFormField(
        labelText: "Item Description",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.itemDescription = value;
        },
      ),
      AppTextFormField(
        labelText: "Request Description",
        // validator: (value) {
        //   if ((value ?? "").isEmpty) return "Mandatory";
        //   return null;
        // },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.requestDescription = value;
        },
      ),
    ];
  }

  List<Widget> assetSection() {
    return [
      InfoHeader16Widget('Asset Details'.addTranslation),
      AppTextFormField(
        labelText: "Asset Name",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.assetName = value;
        },
      ),
      AppTextFormField(
        labelText: "Model",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.model = value;
        },
      ),
      AppTextFormField(
        labelText: "Manufacturer",
        validator: (value) {
          if ((value ?? "").isEmpty) return "Mandatory";
          return null;
        },
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.manufacturer = value;
        },
      ),
      SingleItemDropDownMenu<Lookup, DemoPeriodLookupProvider>(
        context: context,
        height: 56.toScreenHeight,
        title: "Demo Period",
        initialValue: _demoFormModel.demoPeriod,
        showShadow: false,
        validator: (value) {
          if (value == null) return "Mandatory";
          return null;
        },
        backgroundColor: AppColor.fieldBgColor(context),
        showAsBottomSheet: true,
        onSelect: (value) {
          _demoFormModel.demoPeriod = value;
          setState(() {});
        },
      ),
    ];
  }

  List<Widget> vendorDetailsSection() {
    return [
      InfoHeader16Widget('Vendor Details'.addTranslation),
      AppTextFormField(
        labelText: 'Vendor Name'.addTranslation,
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.vendorName = value;
        },
      ),
      AppTextFormField(
        labelText: 'Representative Name'.addTranslation,
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.text,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.vendorRepresentativeName = value;
        },
      ),
      AppTextFormField(
        // controller: vendorPhoneController,
        labelText: "Contact Number",
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.phone,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.vendorContactNumber = value;
        },
      ),
      AppTextFormField(
        labelText: "Email",
        // controller: vendorEmailController,
        style: Theme.of(context).textTheme.titleMedium,
        backgroundColor: AppColor.fieldBgColor(context),
        labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
        showShadow: false,
        textInputType: TextInputType.emailAddress,
        textInputAction: TextInputAction.next,
        onChange: (value) {
          _demoFormModel.vendorEmail = value;
        },
      ),
    ];
  }

  List<Widget> attachmentSection() {
    return [
      InfoHeader16Widget('Attachments'.addTranslation),
      // SingleItemDropDownMenu<Lookup, DemoDocumentLookupProvider>(
      //   context: context,
      //   height: 56.toScreenHeight,
      //   title: "Document Type",
      //   initialValue: demoDocumentLookup,
      //   showShadow: false,
      //   validator: (value) {
      //     if (value == null) return "Mandatory";
      //     return null;
      //   },
      //   backgroundColor: AppColor.fieldBgColor(context),
      //   showAsBottomSheet: true,
      //   onSelect: (value) {
      //     demoDocumentLookup = value;
      //     setState(() {});
      //   },
      // ),
      AttachmentPicker(
        label: context.translation.attachments,
        attachment: _attachments,
        buttonColor: AppColor.primary10.withOpacity(demoDocumentLookup != null ? 1 : .4),
        onlyImages: false,
        enabled: demoDocumentLookup != null,
        documentType: demoDocumentLookup,
        showAsListView: true,
        buttonIcon: 'image-plus'.toSvgAsset(color: (AppColor.primary10)),
        // onChange: (attachments) {
        //   _attachments = attachments;
        //   setState(() {});
        // },
      ),
    ];
  }

  Future<void> _submit() async {
    FocusScope.of(context).unfocus();
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      _demoFormModel.id = 0;
      _demoFormModel.demoAttachment = [];
      for (var item in _attachments) {
        String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
        _demoFormModel.demoAttachment?.add(GenericAttachmentModel(
          id: 0,
          name: fileName,
          moduleReferenceId: 0,
          documentType: item.documentType,
        ));
      }
      Utils.showLoading(context);
      DemoProvider demoProvider = Provider.of<DemoProvider>(context, listen: false);
      bool isSuccess = await demoProvider.addDemoRequest(_demoFormModel.toJson());
      Utils.hideLoading(context);
      if (isSuccess) {
        Navigator.pop(context);
      }
    }
  }
}
