import 'dart:developer';
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/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/modules/asset_delivery_module/models/technical_inspection_asset_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/asset_delivery_utils.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/search_asset_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/status_checklist_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/technical_inpection_asset_card_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/technical_inpection/update_child_asset_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.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 'package:test_sa/providers/loading_list_notifier.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 '../../../../models/new_models/department.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class UpdateParentAssetView extends StatefulWidget {
  final TechnicalInspectionAssetModel assetModel;
  final int? lineId;
  final int? tableItemId;
  final int? costCenterItemId;

  UpdateParentAssetView({
    Key? key,
    required this.assetModel,
    this.lineId,
    this.tableItemId,
    this.costCenterItemId,
  }) : super(key: key);

  @override
  State<UpdateParentAssetView> createState() => _UpdateParentAssetViewState();
}

class _UpdateParentAssetViewState extends State<UpdateParentAssetView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<InspectionChecklistItem> checkList = [];
  late SiteProvider siteProvider;
  late AssetDeliveryProvider assetDeliveryProvider;
  late TextEditingController assetNumberCtrl;
  late TextEditingController serialNoCtrl;
  late TextEditingController systemIdCtrl;

  @override
  void initState() {
    siteProvider = Provider.of<SiteProvider>(context, listen: false);
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    assetNumberCtrl = TextEditingController();
    serialNoCtrl = TextEditingController();
    systemIdCtrl = TextEditingController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      populateForm();
    });
    super.initState();
  }

  void populateForm() async {
    assetDeliveryProvider.isLoading = true;
    assetDeliveryProvider.setParentModel(widget.assetModel);
    if (widget.assetModel.site != null) {
      await assetDeliveryProvider.getSiteData(siteId: widget.assetModel.site?.id, model: assetDeliveryProvider.parentFormModel);
    } else {
      if (siteProvider.items.isEmpty) {
        await siteProvider.getData();
      }
    }
    populateTextFields(model: assetDeliveryProvider.parentFormModel);
    assetDeliveryProvider.isLoading = false;
  }

  void populateTextFields({required TechnicalInspectionAssetModel model}) {
    assetNumberCtrl.text = model.assetNumber ?? '';
    serialNoCtrl.text = model.serialNo ?? '';
    systemIdCtrl.text = model.systemId ?? '';
    setState(() {});
  }

  @override
  void dispose() {
    assetNumberCtrl.dispose();
    serialNoCtrl.dispose();
    systemIdCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'Parent Details'.addTranslation),
      body: Form(
        key: _formKey,
        child: Consumer<AssetDeliveryProvider>(builder: (context, provider, child) {
          return provider.isLoading
              ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
              : Column(
                  children: [
                    SingleChildScrollView(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            inspectionDetailsForm(lineId: widget.lineId, provider: provider).toShadowContainer(context, borderRadius: 20, padding: 12),
                            20.height,
                            Row(
                              children: [
                                Text(
                                  "Test List",
                                  style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
                                ),
                                8.width,
                                'web_link_icon'.toSvgAsset().onPress(() {
                                  openInspectionChecklist(context);
                                }),
                              ],
                            ),
                            16.height,
                            childList(
                              context: context,
                              provider: provider,
                            )
                          ],
                        )).expanded,
                    FooterActionButton.footerContainer(context: context, child: AppFilledButton(buttonColor: AppColor.primary10, label: 'Save'.addTranslation, maxWidth: true, onPressed: _saveTap)),
                  ],
                );
        }),
      ),
    );
  }

  Widget childList({required BuildContext context, required AssetDeliveryProvider provider}) {
    final List<TechnicalInspectionAssetModel> assetDeliveryTableList = provider.parentFormModel.childAssetList ?? [];
    return ListView.separated(
      itemCount: assetDeliveryTableList.length,
      separatorBuilder: (_, __) => 8.height,
      padding: EdgeInsets.zero,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (listContext, itemIndex) {
        TechnicalInspectionAssetModel model = assetDeliveryTableList[itemIndex];
        return TechnicalInspectionAssetCard(
          assetModel: model,
          ischild: true,
          editPress: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => UpdateChildAssetView(
                          assetModel: model,
                          index: itemIndex,
                        )));
          },
          isViewOnly: false,
        );
      },
    );
  }

  /// Need to make reuseable as used in parent and child both.

  Widget inspectionDetailsForm({
    int? lineId,
    required AssetDeliveryProvider provider,
  }) {
    TechnicalInspectionAssetModel model = provider.parentFormModel;
    return Column(
      children: [
        //Replace with simple container...
        AppTextFormField(
          labelText: 'Asset Number'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          controller: assetNumberCtrl,
          initialValue: model.assetNumber,
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          textInputType: TextInputType.number,
          showShadow: false,
          enable: false,
          style: Theme.of(context).textTheme.titleMedium,
        ).onPress(() async {
          var data = await Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => TechnicalInspectionSearchAssetView(
                        lineId: lineId,
                      )));
          if (data != null) {
            TechnicalInspectionAssetModel? assetModel = await provider.getAssetDetails(assetId: data?.id);

            if (assetModel != null) {
              provider.setParentModel(assetModel);
              if (assetModel.site != null) {
                await provider.getSiteData(siteId: assetModel.site?.id, model: provider.parentFormModel);
              }
              assetModel.assetDeliveryInternalDetailAssetId = assetModel.id;
              assetModel.id = 0;
              if (assetModel.childAssetList != null && assetModel.childAssetList!.isNotEmpty) {
                for (var asset in assetModel.childAssetList!) {
                  asset.assetDeliveryInternalDetailAssetChildId = asset.id;
                  asset.id = 0;
                }
              }
              provider.setParentModel(assetModel);
              log('child list length ${assetModel.childAssetList?.length}');

              populateTextFields(model: provider.parentFormModel);
            }
          }
        }),
        8.height,
        AppTextFormField(
          labelText: 'Asset Name'.addTranslation,
          // backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.modelDefinition?.assetName,
          textAlign: TextAlign.center,
          enable: false,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Model'.addTranslation,
          // backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.modelDefinition?.model,
          textAlign: TextAlign.center,
          enable: false,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Manufacturer'.addTranslation,
          // backgroundColor: AppColor.fieldBgColor(context),
          initialValue: model.modelDefinition?.manufacturer ?? '',
          textAlign: TextAlign.center,
          enable: false,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'Serial Number'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          controller: serialNoCtrl,
          initialValue: model.serialNo ?? '',
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          textInputType: TextInputType.number,
          showShadow: false,
          onSaved: (value) {
            model.serialNo = value;
          },
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        AppTextFormField(
          labelText: 'System ID'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          controller: systemIdCtrl,
          initialValue: model.systemId ?? '',
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          onSaved: (value) {
            model.systemId = value;
          },
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        SingleItemDropDownMenu<Site, SiteProvider>(
          context: context,
          title: 'Site',
          initialValue: model.site,
          loading: provider.isSiteLoading,
          showAsBottomSheet: true,
          backgroundColor: AppColor.fieldBgColor(context),
          showShadow: false,
          // enabled: false,
          onSelect: (value) {
            if (value == null) {
              return;
            }
            model.site = value;
            model.building = null;
            model.floor = null;
            model.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Building, NullableLoadingProvider>(
          context: context,
          title: 'Building',
          backgroundColor: AppColor.fieldBgColor(context),
          showAsBottomSheet: true,
          loading: provider.isSiteLoading,
          showShadow: false,
          initialValue: model.building,
          enabled: model.site?.buildings?.isNotEmpty ?? false,
          staticData: model.site?.buildings ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            model.building = value;
            model.floor = null;
            model.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
          context: context,
          showAsBottomSheet: true,
          backgroundColor: AppColor.fieldBgColor(context),
          loading: provider.isSiteLoading,
          showShadow: false,
          title: 'Floor',
          initialValue: model.floor,
          enabled: model.building?.floors?.isNotEmpty ?? false,
          staticData: model.building?.floors ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            model.floor = value;
            model.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Department, NullableLoadingProvider>(
          context: context,
          title: 'Department',
          backgroundColor: AppColor.fieldBgColor(context),
          loading: provider.isSiteLoading,
          showAsBottomSheet: true,
          showShadow: false,
          initialValue: model.department,
          enabled: model.floor?.departments?.isNotEmpty ?? false,
          staticData: model.floor?.departments ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            model.department = value;
            model.room = null;
            setState(() {});
          },
        ),

        8.height,
        ADatePicker(
          label: 'Installation Date'.addTranslation,
          hideShadow: true,
          height: 56.toScreenHeight,
          backgroundColor: AppColor.fieldBgColor(context),
          date: model.installationDate,
          //Need to check whare the picker start for now start from start of year
          from: DateTime(DateTime.now().year, 1, 1),
          formatDateWithTime: true,
          onDatePicker: (selectedDate) {
            showThemedTimePicker(
              context: context,
              initialTime: TimeOfDay.now(),
            ).then((selectedTime) {
              if (selectedTime != null) {
                model.installationDate = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
                setState(() {});
              }
            });
          },
        ),
        8.height,
      ],
    );
  }

  ///Need to check which details show here...

  void _saveTap() async {
    if (!_formKey.currentState!.validate()) return;
    if (assetDeliveryProvider.parentFormModel.installationDate == null) {
      "Installation Date is Required".showToast;
      return;
    }
    _formKey.currentState!.save();
    assetDeliveryProvider.parentFormModel.lineId = widget.lineId;

    assetDeliveryProvider.parentFormModel.tableItemId = widget.tableItemId;
    assetDeliveryProvider.parentFormModel.costCenterId = widget.costCenterItemId;
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await assetDeliveryProvider.saveTechnicalInspectionAssetData(model: assetDeliveryProvider.parentFormModel).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context, true);
      }
    });
  }

  Future<void> openInspectionChecklist(BuildContext context) async {
    applyInspectionFlagsToChecklist(model: assetDeliveryProvider.parentFormModel);
    final result = await Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => InspectionCheckListView(
                  initialValues: checkList,
                )));

    if (result != null) {
      checkList = result;
      setState(() {});
    }
    buildInspectionPayload(checkList);
  }

  bool _isPass(List<InspectionChecklistItem> list, String title) {
    return list
            .firstWhere(
              (e) => e.title == title,
              orElse: () => InspectionChecklistItem(status: 'FAIL'),
            )
            .status ==
        'true';
  }

  buildInspectionPayload(List<InspectionChecklistItem> checklist) {
    assetDeliveryProvider.parentFormModel.flagphysicalInspection = _isPass(checklist, 'Physical Inspection As Per Manufacturer Instructions');
    assetDeliveryProvider.parentFormModel.flagFunctionPerformance = _isPass(checklist, 'Functional Performance As Per Results Of Manufacturer Recommended Check List');
    assetDeliveryProvider.parentFormModel.flagGroundingResistance = _isPass(checklist, 'Grounding Resistance: Ω');
    assetDeliveryProvider.parentFormModel.flagChassiss = _isPass(checklist, 'Chassis Leakage Current: µA');
    assetDeliveryProvider.parentFormModel.flagLeadsLeakage = _isPass(checklist, 'Leads Leakage Current: µA');
    assetDeliveryProvider.parentFormModel.flagAlert = _isPass(checklist, 'This Device Is Not Subject To Any Alert Or Recall Until The Date Of Preparation Of This Inspection Form');
  }

  void applyInspectionFlagsToChecklist({
    required TechnicalInspectionAssetModel model,
  }) {
    if (checkList.isEmpty) {
      checkList = AssetDeliveryUtils.inspectionChecklist;
    }
    for (final item in checkList) {
      switch (item.value) {
        case 'flagphysicalInspection':
          item.status = _statusFromBool(model.flagphysicalInspection);
          break;

        case 'flagFunctionPerformance':
          item.status = _statusFromBool(model.flagFunctionPerformance);
          break;

        case 'flagGroundingResistance':
          item.status = _statusFromBool(model.flagGroundingResistance);
          break;

        case 'flagChassiss':
          item.status = _statusFromBool(model.flagChassiss);
          break;

        case 'flagLeadsLeakage':
          item.status = _statusFromBool(model.flagLeadsLeakage);
          break;

        case 'flagAlert':
          item.status = _statusFromBool(model.flagAlert);
          break;
      }
    }
  }

  String _statusFromBool(bool? value) {
    return value == true ? 'PASS' : 'FAIL';
  }
}
