// import 'dart:developer';
//
// import 'package:flutter/foundation.dart';
// 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/lookup.dart';
// import 'package:test_sa/modules/asset_delivery_module/models/end_user_asset_details_model.dart';
// import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
// import 'package:test_sa/modules/asset_delivery_module/provider/end_user_rejection_reason_lookup_provider.dart';
// import 'package:test_sa/modules/asset_delivery_module/provider/end_user_status_lookup_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 '../../../../new_views/common_widgets/app_filled_button.dart';
// import '../../../../new_views/common_widgets/default_app_bar.dart';
//
// class UpdateEndUserAssetDetailsView extends StatefulWidget {
//   EndUserAssetDetailsModel? assetDetailsModel;
//   String? costCenterName;
//   int? tableId;
//
//   UpdateEndUserAssetDetailsView({Key? key, this.assetDetailsModel, this.costCenterName, this.tableId}) : super(key: key);
//
//   @override
//   State<UpdateEndUserAssetDetailsView> createState() => _UpdateEndUserAssetDetailsViewState();
// }
//
// class _UpdateEndUserAssetDetailsViewState extends State<UpdateEndUserAssetDetailsView> {
//   final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
//   final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
//   bool viewOnly = false;
//   late AssetDeliveryProvider assetDeliveryProvider;
//   EndUserAssetDetailsModel model = EndUserAssetDetailsModel();
//   late TextEditingController quantityController;
//   late TextEditingController descriptionController;
//
//   @override
//   void initState() {
//     quantityController = TextEditingController();
//     descriptionController = TextEditingController();
//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       getInitialData();
//     });
//     super.initState();
//   }
//
//   @override
//   void dispose() {
//     super.dispose();
//   }
//
//   void getInitialData() async {
//     assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
//     if (widget.assetDetailsModel != null) {
//       model = EndUserAssetDetailsModel.fromJson(widget.assetDetailsModel!.toJson());
//       model.costCenterName = widget.costCenterName;
//       model.assetDeliveryExternalDeliveryId = widget.tableId;
//       model.status = widget.assetDetailsModel?.status;
//       model.rejectionReason = widget.assetDetailsModel?.rejectionReason;
//     }
//     quantityController.text = model.rejectedQty != null ? model.rejectedQty.toString() : '';
//     descriptionController.text = model.description ?? '';
//     model.type = 'Accessory';
//     setState(() {});
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       key: _scaffoldKey,
//       appBar: DefaultAppBar(
//         title: 'Item Details'.addTranslation,
//         titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
//       ),
//       body: Form(
//         key: _formKey,
//         child: Column(
//           children: [
//             SingleChildScrollView(
//                     padding: const EdgeInsets.all(16),
//                     child: Column(
//                       crossAxisAlignment: CrossAxisAlignment.start,
//                       children: [
//                         SingleItemDropDownMenu<Lookup, EndUserStatusLookupProvider>(
//                           context: context,
//                           height: 56.toScreenHeight,
//                           title: 'Status'.addTranslation,
//                           titleTextColor: AppColor.neutral120,
//                           showShadow: false,
//                           validator: (value) {
//                             if (value == null) return "Please select status";
//                             return null;
//                           },
//                           backgroundColor: AppColor.fieldBgColor(context),
//                           showAsBottomSheet: true,
//                           initialValue: model.status,
//                           onSelect: (status) {
//                             if (status != null) {
//                               model.status = status;
//                               setState(() {});
//                             }
//                           },
//                         ),
//                         8.height,
//                         if (model.type == 'Accessory') ...[
//                           AppTextFormField(
//                             labelText: 'Rejected Quantity'.addTranslation,
//                             controller: quantityController,
//                             backgroundColor: AppColor.fieldBgColor(context),
//                             textAlign: TextAlign.center,
//                             labelStyle: AppTextStyles.textFieldLabelStyle,
//                             textInputType: TextInputType.number,
//                             showShadow: false,
//                             validator: (value) {
//                               if ((value ?? "").isEmpty) return "Mandatory";
//                               return null;
//                             },
//                             onChange: (value) {
//                               if (value.isNotEmpty) {
//                                 model.rejectedQty = model.rejectedQty = num.tryParse(value);
//                                 setState(() {});
//                               }
//                             },
//                             style: Theme.of(context).textTheme.titleMedium,
//                           ),
//                           8.height,
//                           if (model.status?.value == 1 && (model.rejectedQty != null && quantityController.text.isNotEmpty && model.rejectedQty! > 0))
//                             SingleItemDropDownMenu<Lookup, EndUserRejectionReasonLookupProvider>(
//                               context: context,
//                               height: 56.toScreenHeight,
//                               title: 'Rejection Reason '.addTranslation,
//                               validator: (value) {
//                                 if (value == null) return "Please select rejection reason";
//                                 return null;
//                               },
//                               titleTextColor: AppColor.neutral120,
//                               showShadow: false,
//                               backgroundColor: AppColor.fieldBgColor(context),
//                               showAsBottomSheet: true,
//                               initialValue: model.rejectionReason,
//                               onSelect: (reason) {
//                                 if (reason != null) {
//                                   model.rejectionReason = reason;
//                                   setState(() {});
//                                 }
//                               },
//                             ),
//                           8.height,
//                         ],
//                         if (model.status != null && model.status!.value == 2) ...[
//                           SingleItemDropDownMenu<Lookup, EndUserRejectionReasonLookupProvider>(
//                             context: context,
//                             height: 56.toScreenHeight,
//                             title: 'Rejection Reason '.addTranslation,
//                             validator: (value) {
//                               if (value == null) return "Please select rejection reason";
//                               return null;
//                             },
//                             titleTextColor: AppColor.neutral120,
//                             showShadow: false,
//                             backgroundColor: AppColor.fieldBgColor(context),
//                             showAsBottomSheet: true,
//                             initialValue: model.rejectionReason,
//                             onSelect: (reason) {
//                               if (reason != null) {
//                                 model.rejectionReason = reason;
//                                 setState(() {});
//                               }
//                             },
//                           ),
//                           8.height,
//                         ],
//                         AppTextFormField(
//                           controller: descriptionController,
//                           labelText: 'Description'.addTranslation,
//                           backgroundColor: AppColor.fieldBgColor(context),
//                           showShadow: false,
//                           labelStyle: AppTextStyles.textFieldLabelStyle,
//                           alignLabelWithHint: true,
//                           textInputType: TextInputType.multiline,
//                           onChange: (value) {
//                             model.description = value;
//                           },
//                           onSaved: (value) {
//                             model.description = value;
//                           },
//                         ),
//                         8.height,
//                       ],
//                     ).toShadowContainer(context, borderRadius: 20, padding: 12))
//                 .expanded,
//             FooterActionButton.footerContainer(context: context, child: AppFilledButton(buttonColor: AppColor.primary10, label: 'Save'.addTranslation, maxWidth: true, onPressed: _saveTap)),
//           ],
//         ),
//       ),
//     );
//   }
//
//   ///Need to check which details show here...
//
//   void _saveTap() async {
//     if (!_formKey.currentState!.validate()) {
//       return;
//     }
//     _formKey.currentState!.save();
//     log('payload ${model.toJson()}');
//     return;
//     showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
//     await assetDeliveryProvider.saveEndUserAssetDataData(model: model).then((status) async {
//       Navigator.pop(context);
//       if (status) {
//         Navigator.pop(context, true);
//       }
//     });
//   }
// }

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/lookup.dart';
import 'package:test_sa/modules/asset_delivery_module/models/end_user_asset_details_model.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/end_user_rejection_reason_lookup_provider.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/end_user_status_lookup_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 '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class UpdateEndUserAssetDetailsView extends StatefulWidget {
  final EndUserAssetDetailsModel? assetDetailsModel;
  final String? costCenterName;
  final int? tableId;

  const UpdateEndUserAssetDetailsView({
    Key? key,
    this.assetDetailsModel,
    this.costCenterName,
    this.tableId,
  }) : super(key: key);

  @override
  State<UpdateEndUserAssetDetailsView> createState() => _UpdateEndUserAssetDetailsViewState();
}

class _UpdateEndUserAssetDetailsViewState extends State<UpdateEndUserAssetDetailsView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  late AssetDeliveryProvider assetDeliveryProvider;
  EndUserAssetDetailsModel model = EndUserAssetDetailsModel();

  late TextEditingController quantityController;
  late TextEditingController descriptionController;

  @override
  void initState() {
    super.initState();
    quantityController = TextEditingController();
    descriptionController = TextEditingController();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
  }

  void _loadInitialData() {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    if (widget.assetDetailsModel != null) {
      model = EndUserAssetDetailsModel.fromJson(
        widget.assetDetailsModel!.toJson(),
      );
      model.costCenterName = widget.costCenterName;
      model.assetDeliveryExternalDeliveryId = widget.tableId;
      model.status = widget.assetDetailsModel?.status;
      model.rejectionReason = widget.assetDetailsModel?.rejectionReason;
      model.receivedQty = widget.assetDetailsModel?.receivedQty;
    }

    quantityController.text = model.rejectedQty != null ? model.rejectedQty.toString() : '';
    descriptionController.text = model.description ?? '';
    setState(() {});
  }

  bool get _isAccessory => model.type == 'Accessory';

  bool get _isAccepted => model.status?.value == 1;

  bool get _isRejected => model.status?.value == 2;

  bool get _showRejectedQty {
    if (_isAccessory) return true;
    return false;
  }

  bool get _showReceivedQty {
    if (_isAccessory && model.receivedQty != null) return true;
    return false;
  }

  bool get _showRejectionReason {
    if (_isAccessory) {
      if (_isRejected) return true;
      if (_isAccepted && (model.rejectedQty ?? 0) > 0) return true;
      return false;
    }
    if (_isRejected) return true;
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: 'Item Details'.addTranslation,
        titleStyle: AppTextStyles.heading3.copyWith(
          fontWeight: FontWeight.w500,
          color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
        ),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: _formBody(context),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                label: 'Save'.addTranslation,
                maxWidth: true,
                onPressed: _saveTap,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _formBody(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _statusDropdown(),
        8.height,
        if (_showReceivedQty) ...[
          _receivedQtyField(),
          8.height,
        ],
        if (_showRejectedQty) ...[
          _rejectedQtyField(),
          8.height,
        ],
        if (_showRejectionReason) ...[
          _rejectionReasonDropdown(),
          8.height,
        ],
        _descriptionField(),
        8.height,
      ],
    ).toShadowContainer(context, borderRadius: 20, padding: 12);
  }

  Widget _statusDropdown() {
    return SingleItemDropDownMenu<Lookup, EndUserStatusLookupProvider>(
      context: context,
      height: 56.toScreenHeight,
      title: 'Status'.addTranslation,
      titleTextColor: AppColor.neutral120,
      showShadow: false,
      backgroundColor: AppColor.fieldBgColor(context),
      showAsBottomSheet: true,
      initialValue: model.status,
      validator: (value) {
        if (value == null) return 'Please select status';
        return null;
      },
      onSelect: (status) {
        if (status != null) {
          model.status = status;
          model.rejectionReason = null;
          setState(() {});
        }
      },
    );
  }

  Widget _rejectedQtyField() {
    return AppTextFormField(
      labelText: 'Rejected Quantity'.addTranslation,
      controller: quantityController,
      backgroundColor: AppColor.fieldBgColor(context),
      textAlign: TextAlign.center,
      labelStyle: AppTextStyles.textFieldLabelStyle,
      textInputType: TextInputType.number,
      showShadow: false,
      style: Theme.of(context).textTheme.titleMedium,
      validator: (value) {
        if (!_showRejectedQty) return null;
        if ((value ?? '').isEmpty) return 'Mandatory';
        final qty = num.tryParse(value!);
        if (qty == null || qty <= 0) return 'Enter valid quantity';
        return null;
      },
      onChange: (value) {
        model.rejectedQty = value.isNotEmpty ? num.tryParse(value) : null;
        setState(() {});
      },
    );
  }

  Widget _receivedQtyField() {
    return Container(
      padding: const EdgeInsets.all(12),
      width: double.infinity,
      decoration: BoxDecoration(
        color: AppColor.neutral40,
        // color: AppColor.fieldBgColor(context),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Received Qty', style: AppTextStyles.textFieldLabelStyle),
          4.height,
          Text(model.receivedQty.toString(), style: AppTextStyles.textFieldLabelStyle),
        ],
      ),
    );

    AppTextFormField(
      labelText: 'Received Quantity'.addTranslation,
      initialValue: model.receivedQty.toString(),
      textAlign: TextAlign.center,
      labelStyle: AppTextStyles.textFieldLabelStyle,
      showShadow: false,
      enable: false,
      style: Theme.of(context).textTheme.titleMedium,
    );
  }

  Widget _rejectionReasonDropdown() {
    return SingleItemDropDownMenu<Lookup, EndUserRejectionReasonLookupProvider>(
      context: context,
      height: 56.toScreenHeight,
      title: 'Rejection Reason'.addTranslation,
      titleTextColor: AppColor.neutral120,
      showShadow: false,
      backgroundColor: AppColor.fieldBgColor(context),
      showAsBottomSheet: true,
      initialValue: model.rejectionReason,
      validator: (value) {
        if (!_showRejectionReason) return null;
        if (value == null) return 'Please select rejection reason';
        return null;
      },
      onSelect: (reason) {
        if (reason != null) {
          model.rejectionReason = reason;
          setState(() {});
        }
      },
    );
  }

  Widget _descriptionField() {
    return AppTextFormField(
      controller: descriptionController,
      labelText: 'Description'.addTranslation,
      backgroundColor: AppColor.fieldBgColor(context),
      showShadow: false,
      labelStyle: AppTextStyles.textFieldLabelStyle,
      alignLabelWithHint: true,
      textInputType: TextInputType.multiline,
      onChange: (value) => model.description = value,
      onSaved: (value) => model.description = value,
    );
  }

  void _saveTap() async {
    if (!_formKey.currentState!.validate()) return;

    _formKey.currentState!.save();
    log('payload ${model.toJson()}');

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const AppLazyLoading(),
    );

    final status = await assetDeliveryProvider.saveEndUserAssetDataData(model: model);

    Navigator.pop(context);

    if (status) {
      Navigator.pop(context, true);
    }
  }
}
