import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter/services.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/modules/asset_delivery_module/models/cost_center_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/end_user_asset_details_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/end_user_acceptance/end_user_asset_detail_card.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/delivery_inspection/oracle_user_autocomplete_field.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/end_user_acceptance/update_end_user_asset_details_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/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/e_signature/e_signature.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class UpdateEndUserCostCenterDetailsView extends StatefulWidget {
  int? tableItemId;
  CostCenterModel? costCenterModel;
  bool? isHmg;

  UpdateEndUserCostCenterDetailsView({
    Key? key,
    this.tableItemId,
    this.costCenterModel,
    this.isHmg,
  }) : super(key: key);

  @override
  State<UpdateEndUserCostCenterDetailsView> createState() => _UpdateEndUserCostCenterDetailsViewState();
}

class _UpdateEndUserCostCenterDetailsViewState extends State<UpdateEndUserCostCenterDetailsView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool viewOnly = false;
  CostCenterModel model = CostCenterModel();
  List<EndUserAssetDetailsModel> assetList = [];
  late AssetDeliveryProvider assetDeliveryProvider;
  Uint8List? newSignature;
  String? endUserSignature;
  bool isLoading = false;
  late TextEditingController acceptedByController;
  late TextEditingController acceptedByEmailController;

  @override
  void initState() {
    acceptedByController = TextEditingController();
    acceptedByEmailController = TextEditingController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  void getInitialData() async {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);

    if (widget.costCenterModel != null) {
      model = CostCenterModel.fromJson(widget.costCenterModel!.toEndUserAcceptanceFormJson());
      _fillControllers();
    }
    setState(() {
      isLoading = true;
    });
    assetList = await assetDeliveryProvider.getEndUserAssetList(tableItemId: widget.tableItemId, costCenterName: widget.costCenterModel?.costCenterName);
    setState(() {
      isLoading = false;
    });
  }

  void _fillControllers() {
    acceptedByController.text = model.acceptedBy ?? '';
    acceptedByEmailController.text = model.acceptedByEmail ?? '';
  }

  @override
  void dispose() {
    acceptedByController.dispose();
    acceptedByEmailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: 'End-User Acceptance'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    inspectionDetailsForm().toShadowContainer(context, borderRadius: 20, padding: 12),

                    ///Need to implement later as discuss with Ahmed.
                    // Text(
                    //   "Acceptance Form",
                    //   style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
                    // ),
                    // 6.height,
                    // Row(
                    //   children: [
                    //     'warning_icon'.toSvgAsset(height: 16, width: 16),
                    //     6.width,
                    //     Text(
                    //       'Review the acceptance form'.addTranslation,
                    //       style: AppTextStyles.bodyText2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral120),
                    //     ),
                    //     6.width,
                    //     'web_link_icon'.toSvgAsset(height: 20, width: 20),
                    //   ],
                    // ),
                    20.height,
                    Text(
                      "Items",
                      style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
                    ),
                    16.height,
                    endUserAssetList(context),
                  ],
                )).expanded,
            FooterActionButton.footerContainer(context: context, child: AppFilledButton(buttonColor: AppColor.primary10, label: 'Save'.addTranslation, maxWidth: true, onPressed: _saveTap)),
          ],
        ),
      ),
    );
  }

  Widget endUserAssetList(BuildContext context) {
    return isLoading
        ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center
        : ListView.separated(
            itemCount: assetList.length,
            separatorBuilder: (_, __) => 8.height,
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (listContext, itemIndex) {
              EndUserAssetDetailsModel model = assetList[itemIndex];
              return EndUserAssetDetailCard(
                assetModel: model,
                isViewOnly: viewOnly,
                editPress: () async {
                  bool isRefresh = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => UpdateEndUserAssetDetailsView(
                                assetDetailsModel: model,
                                costCenterName: widget.costCenterModel?.costCenterName,
                                tableId: widget.tableItemId,
                              )));
                  if (isRefresh) {
                    getInitialData();
                  }
                },
              );
            },
          );
  }

  Widget inspectionDetailsForm() {
    return Column(
      children: [
        ADatePicker(
          label: 'Accepted Date'.addTranslation,
          hideShadow: true,
          height: 56.toScreenHeight,
          backgroundColor: AppColor.fieldBgColor(context),
          date: model.acceptanceDate,
          from: DateTime(DateTime.now().year, 1, 1),
          formatDateWithTime: true,
          onDatePicker: (selectedDate) {
            showThemedTimePicker(
              context: context,
              initialTime: TimeOfDay.now(),
            ).then((selectedTime) {
              if (selectedTime != null) {
                model.acceptanceDate = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
                setState(() {});
              }
            });
          },
        ),
        8.height,
        if (widget.isHmg == true) ...[
          OracleUserAutoCompleteField(
            clearAfterPick: false,
            initialValue: model.acceptedBy ?? '',
            label: 'Accepted By'.addTranslation,
            onPick: (value) {
              model.acceptedBy = value.fullName;
              model.acceptedByEmail = value.employeeEmail;
              acceptedByEmailController.text = value.employeeEmail ?? '';
              setState(() {});
            },
            onChanged: (value) {},
          ),
          8.height,
        ] else ...[
          AppTextFormField(
            labelText: 'Accepted By'.addTranslation,
            backgroundColor: AppColor.fieldBgColor(context),
            controller: acceptedByController,
            textAlign: TextAlign.center,
            labelStyle: AppTextStyles.textFieldLabelStyle,
            showShadow: false,
            validator: (value) {
              if ((value ?? "").isEmpty) return "Mandatory";
              return null;
            },
            onChange: (value) {
              model.acceptedBy = value;
            },
            style: Theme.of(context).textTheme.titleMedium,
          ),
          8.height,
        ],
        AppTextFormField(
          labelText: 'Accepted By Email'.addTranslation,
          backgroundColor: AppColor.fieldBgColor(context),
          controller: acceptedByEmailController,
          validator: (value) {
            if ((value ?? "").isEmpty) return "Mandatory";
            return null;
          },
          onChange: (value) {
            model.acceptedByEmail = value;
          },
          textAlign: TextAlign.center,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          showShadow: false,
          enable: widget.isHmg == true ? false : true,
          style: Theme.of(context).textTheme.titleMedium,
        ),
        8.height,
        ESignature(
          title: 'End User Signature',
          oldSignature: model.acceptedBySignature,
          newSignature: newSignature,
          backgroundColor: AppColor.neutral100,
          showShadow: false,
          onChange: (signature) {
            updateSignature(signature: signature);
          },
        )
      ],
    );
  }

  void updateSignature({Uint8List? signature}) {
    if (signature == null || signature.isEmpty) {
      setState(() {
        newSignature = null;
        model.acceptedBySignature = null;
      });
      return;
    }
    setState(() {
      newSignature = signature;
      model.acceptedBySignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
    });
  }

  void _saveTap() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }
    if (model.acceptanceDate == null) {
      "Select Accepted date".showToast;
      return;
    }
    if (widget.isHmg == true) {
      if ((model.acceptedBy ?? '').isEmpty || (model.acceptedByEmail ?? '').isEmpty) {
        'Accepted By and Email are required'.addTranslation.showToast;
        return;
      }
    }
    if (model.acceptedBySignature == null || model.acceptedBySignature!.isEmpty) {
      'Signature is required'.addTranslation.showToast;
      return;
    }
    _formKey.currentState!.save();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    model.assetDeliveryExternalDetailId = widget.tableItemId;
    await assetDeliveryProvider.saveEndUserFormData(model: model).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context, true);
      }
    });
  }
}
