import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_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/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.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/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_data_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_form_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_supplier_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/item_type_provider.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/medical_gas_inspection_provider.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/medical_gas_supplier_provider.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/order_type_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_lazy_loading.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/gas_request_providers/site_provider.dart';
import '../../../../../../new_views/common_widgets/default_app_bar.dart';

class CreateMedicalGasRequestPage extends StatefulWidget {
  static const String id = "/create-medical-gas";
  final MedicalGasDataModel? dataModel;

  CreateMedicalGasRequestPage({Key? key, this.dataModel}) : super(key: key);

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

class _CreateMedicalGasRequestPageState extends State<CreateMedicalGasRequestPage> with TickerProviderStateMixin {
  final List<GenericAttachmentModel> attachments = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TaskType? selectedType;
  MedicalGasFormModel _medicalGasFormModel = MedicalGasFormModel();
  MedicalGasSupplierModel? medicalGasInfo;
  late MedicalGasInspectionProvider medicalGasInspectionProvider;
  late SiteProvider siteProvider;
  bool isGasInfoLoading = false;

  @override
  void initState() {
    super.initState();
    // Provider.of<MedicalGasSupplierProvider>(context, listen: false).reset();
    medicalGasInspectionProvider = Provider.of<MedicalGasInspectionProvider>(context, listen: false);
    siteProvider = Provider.of<SiteProvider>(context, listen: false);
    _populateFormData();
  }

  _populateFormData() {
    if (siteProvider.items.isEmpty) {
      siteProvider.reset();
    }
    if (widget.dataModel != null) {
      MedicalGasDataModel dataModel = widget.dataModel!;
      _medicalGasFormModel = MedicalGasFormModel(
        id: dataModel.id,
        orderType: Lookup(id: dataModel.requestOrderTypeId, name: dataModel.requestOrderType),
        itemType: Lookup(id: dataModel.itemTypeId, name: dataModel.itemType),
        site: Site(id: dataModel.siteId, custName: dataModel.site),
        supplier: MedicalGasSupplierModel(id: dataModel.supplierId, supplier: dataModel.supplier),
      );
      List<AttributeInfo> attributeInfo = [];
      dataModel.requestDetailDtos.forEach((v) {
        attributeInfo.add(AttributeInfo.fromJson(v.toJson()));
      });
      medicalGasInfo = MedicalGasSupplierModel(
        supplierContact: dataModel.contact,
        supplierEmail: dataModel.email,
        attributeInfo: attributeInfo,
      );
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'Medical Gas Inspection'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  SingleItemDropDownMenu<Lookup, MedicalGasOrderTypeProvider>(
                    context: context,
                    title: "Order Type",
                    validator: (value) {
                      if (value == null) return "Please select order type";
                      return null;
                    },
                    initialValue: _medicalGasFormModel.orderType,
                    showShadow: false,
                    // backgroundColor: AppColor.fieldBgColor(context),
                    showAsBottomSheet: true,
                    onSelect: (value) {
                      _medicalGasFormModel.orderType = value;
                    },
                  ),
                  8.height,
                  SingleItemDropDownMenu<Lookup, MedicalGasItemTypeProvider>(
                    context: context,
                    title: "Item Type",
                    validator: (value) {
                      if (value == null) return "Please select item type";
                      return null;
                    },
                    initialValue: _medicalGasFormModel.itemType,
                    showShadow: false,
                    showAsBottomSheet: true,
                    onSelect: (value) {
                      _medicalGasFormModel.itemType = value;
                      setState(() {});
                      setGasInfo();
                    },
                  ),
                  8.height,
                  SingleItemDropDownMenu<Site, SiteProvider>(
                    context: context,
                    title: context.translation.site,
                    initialValue: _medicalGasFormModel.site,
                    showShadow: false,
                    validator: (value) {
                      if (value == null) return "Please select a site";
                      return null;
                    },
                    // backgroundColor: AppColor.fieldBgColor(context),
                    showAsBottomSheet: true,
                    onSelect: (value) {
                      _medicalGasFormModel.site = value;
                      setState(() {});
                      setGasInfo();
                    },
                  ),
                  8.height,
                  SingleItemDropDownMenu<MedicalGasSupplierModel, MedicalGasSupplierProvider>(
                    context: context,
                    title: context.translation.supplier,
                    initialValue: _medicalGasFormModel.supplier,
                    showAsBottomSheet: true,
                    // backgroundColor: AppColor.fieldBgColor(context),
                    showShadow: false,
                    validator: (value) {
                      if (value == null) return "Please select a supplier";
                      return null;
                    },
                    onSelect: (value) {
                      setState(() {
                        _medicalGasFormModel.supplier = value;
                      });
                      setGasInfo();
                    },
                  ),
                  if (medicalGasInfo != null) medicalGasInfoWidget(),
                ],
              ).toShadowContainer(context, borderRadius: 20),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: Row(
                children: [
                  AppFilledButton(
                    buttonColor: AppColor.primary10,
                    label: 'Save'.addTranslation,
                    onPressed: () {
                      _update(isSubmitted: false);
                    },
                    // buttonColor: AppColor.primary10,
                  ).expanded,
                  8.width,
                  AppFilledButton(
                    buttonColor: AppColor.primary10,
                    label: 'Submit'.addTranslation,
                    onPressed: () {
                      _update(isSubmitted: true);
                    },
                    // buttonColor: AppColor.primary10,
                  ).expanded,
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void setGasInfo() async {
    if (_medicalGasFormModel.itemType != null && _medicalGasFormModel.site != null && _medicalGasFormModel.supplier != null) {
      setState(() {
        isGasInfoLoading = true;
      });
      medicalGasInfo =
          await medicalGasInspectionProvider.getMedicalGasInfo(itemTypeId: _medicalGasFormModel.itemType!.id, supplierId: _medicalGasFormModel.supplier!.id, siteId: _medicalGasFormModel.site!.id);
      setState(() {
        isGasInfoLoading = false;
      });
    }
  }

  Widget medicalGasInfoWidget() {
    return isGasInfoLoading
        ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              8.height,
              'Supplier Contact: ${medicalGasInfo?.supplierContact ?? "-"}'.bodyText(context).custom(color: AppColor.black10),
              8.height,
              'Supplier Email: ${medicalGasInfo?.supplierEmail ?? "-"}'.bodyText(context).custom(color: AppColor.black10),
              8.height,
              'Items'.addTranslation.bodyText(context).custom(color: AppColor.textColor(context)),
              8.height,
              // MedicalGasItemsListView(
              //   itemsList: medicalGasInfo?.attributeInfo ?? [],
              // ),
              if (medicalGasInfo!.attributeInfo!.isNotEmpty)
                ListView.separated(
                  separatorBuilder: (_, __) => 12.height,
                  itemCount: medicalGasInfo!.attributeInfo!.length,
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.zero,
                  itemBuilder: (context, index) {
                    AttributeInfo model = medicalGasInfo!.attributeInfo![index];
                    return AppTextFormField(
                      labelText: model.itemName,
                      hintText: 'Enter Quantity'.addTranslation,
                      backgroundColor: AppColor.fieldBgColor(context),
                      initialValue: model.requestedQuantity != null ? model.requestedQuantity?.toStringAsFixed(0) : '',
                      // initialValue: model.value != null ? model.value.toString() : '',
                      textAlign: TextAlign.center,
                      // validator: (value) {
                      //   if (value == null || value.trim().isEmpty) {
                      //     return "This field is required";
                      //   }
                      //
                      //   final intVal = int.tryParse(value);
                      //   if (intVal == null) {
                      //     return "Enter a valid number";
                      //   }
                      //
                      //   if (intVal <= 0) {
                      //     return "Value must be greater than 0";
                      //   }
                      //
                      //   return null;
                      // },
                      textInputType: TextInputType.number,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      showShadow: false,
                      onChange: (value) {
                        if (value.isNotEmpty) {
                          model.requestedQuantity = int.tryParse(value);
                        }
                      },
                      style: Theme.of(context).textTheme.titleMedium,
                    );
                  },
                )
            ],
          );
  }

  Future<void> _update({bool isSubmitted = false}) async {
    if (!_formKey.currentState!.validate()) return;
    _formKey.currentState?.save();
    if (medicalGasInfo != null && medicalGasInfo!.attributeInfo!.isNotEmpty) {
      _medicalGasFormModel.gasRequestDetail = [];
      for (var item in medicalGasInfo!.attributeInfo!) {
        _medicalGasFormModel.gasRequestDetail?.add(MedicalGasFormDetailModel(
          id: widget.dataModel != null ? item.id : 0,
          medicalGasAttributeId: item.medicalGasAttributeId ?? item.id,
          requestedQuantity: item.requestedQuantity,
        ));
      }
    }

    _medicalGasFormModel.isSubmitted = isSubmitted;
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await medicalGasInspectionProvider.saveMedicalGas(model: _medicalGasFormModel).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context, true);
        AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
        allRequestsProvider.reset();
        await allRequestsProvider.getAllRequests(context, typeTransaction: 14);
      } else {
        //This should be handled from backend.
        Fluttertoast.showToast(msg: 'Something went wrong', toastLength: Toast.LENGTH_LONG);
      }
    });
  }
}
