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

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/providers/api/all_requests_provider.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_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/timer_model.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.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_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';

import '../../../../extensions/text_extensions.dart';
import '../../../../models/new_models/gas_refill_model.dart';
import '../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';
import '../../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../widgets/timer/app_timer.dart';

class UpdateGasRefillRequest extends StatefulWidget {
  static const String id = "/gas-refill-form";
  final GasRefillModel? gasRefillModel;

  const UpdateGasRefillRequest({this.gasRefillModel, Key? key}) : super(key: key);

  @override
  State<UpdateGasRefillRequest> createState() => _UpdateGasRefillRequestState();
}

class _UpdateGasRefillRequestState extends State<UpdateGasRefillRequest> {
  final bool _isLoading = false;
  double totalWorkingHours = 0.0;

  late UserProvider _userProvider;
  GasRefillProvider? _gasRefillProvider;
  GasRefillDetails _currentDetails = GasRefillDetails();
  final TextEditingController _deliveredQuantityController = TextEditingController();
  final TextEditingController _commentController = TextEditingController();
  final TextEditingController _workingHoursController = TextEditingController();

  final GasRefillModel _formModel = GasRefillModel(gasRefillDetails: []);
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _firstTime = true;

  Lookup? _deliveredQuantity;
  List<GenericAttachmentModel> _attachments = [];

  static List<Lookup> deliveredQuantity = [
    Lookup(name: "1", id: 1, value: 1),
    Lookup(name: "2", id: 2, value: 2),
    Lookup(name: "3", id: 3, value: 3),
    Lookup(name: "4", id: 4, value: 4),
    Lookup(name: "5", id: 5, value: 5)
  ];

  @override
  void initState() {
    super.initState();
    _gasRefillProvider ??= Provider.of<GasRefillProvider>(context, listen: false);

    if (widget.gasRefillModel != null) {
      _formModel.fromGasRefillModel(widget.gasRefillModel!);

      totalWorkingHours = _formModel.gasRefillTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDate!).difference(DateTime.parse(item.startDate!)).inSeconds) ?? 0;
      _commentController.text = _formModel.techComment ?? "";
      try {
        _deliveredQuantity = deliveredQuantity.singleWhere((element) => element.value == _formModel.gasRefillDetails![0].deliverdQty);
        _currentDetails.deliverdQty = _deliveredQuantity!.value;
      } catch (ex) {}
    }
    if (_formModel.gasRefillAttachments != null && _formModel.gasRefillAttachments!.isNotEmpty) {
      _attachments.addAll(_formModel.gasRefillAttachments!.map((e) => GenericAttachmentModel(id:e.id,name:e.attachmentName!)).toList());
    }
  }

  @override
  void setState(VoidCallback fn) {
    if (mounted) super.setState(() {});
  }

  _onSubmit(BuildContext context, int status) async {
    bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;

    if (isTimerPickerEnable) {
      if (_formModel.timer?.startAt == null && _formModel.gasRefillTimePicker == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (_formModel.gasRefillTimePicker == null) {
        if (_formModel.timer?.startAt == null) {
          Fluttertoast.showToast(msg: "Working Hours Required");
          return false;
        }
        if (_formModel.timer?.endAt == null) {
          Fluttertoast.showToast(msg: "Please Stop The Timer");
          return false;
        }
      }
    } else {
      if (_formModel.timer?.startAt == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (_formModel.timer?.endAt == null) {
        Fluttertoast.showToast(msg: "Please Stop The Timer");
        return false;
      }
    }

    if (_currentDetails.deliverdQty == null) {
      await Fluttertoast.showToast(msg: "Delivered Quantity  is Required");
      return false;
    }
    _formModel.gasRefillDetails = [];
    _formModel.gasRefillDetails?.add(_currentDetails);

    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    _formModel.gasRefillTimers = _formModel.gasRefillTimers ?? [];
    if (_formModel.gasRefillTimePicker != null) {
      int durationInSecond = _formModel.gasRefillTimePicker!.endAt!.difference(_formModel.gasRefillTimePicker!.startAt!).inSeconds;
      _formModel.gasRefillTimers?.add(
        GasRefillTimer(
          id: 0,
          startDate: _formModel.gasRefillTimePicker!.startAt!.toIso8601String(), // Handle potential null
          endDate: _formModel.gasRefillTimePicker!.endAt?.toIso8601String(), // Handle potential null
          workingHours: ((durationInSecond) / 60 / 60),
        ),
      );
    }
    _formModel.timerModelList?.forEach((timer) {
      int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
      _formModel.gasRefillTimers?.add(
        GasRefillTimer(
          id: 0,
          startDate: timer.startAt!.toIso8601String(), // Handle potential null
          endDate: timer.endAt?.toIso8601String(), // Handle potential null
          workingHours: ((durationInSecond) / 60 / 60),
        ),
      );
    });
    _formModel.gasRefillAttachments = [];
    for (var item in _attachments) {
      String fileName = ServiceRequestUtils.isLocalUrl(item.name??'') ? ("${item.name??''.split("/").last}|${base64Encode(File(item.name??'').readAsBytesSync())}") :item.name??'';
      _formModel.gasRefillAttachments?.add(GasRefillAttachments(
          id: item.id, gasRefillId: _formModel.id ?? 0, attachmentName: fileName));
    }

    await _gasRefillProvider?.updateGasRefill(status: status, model: _formModel).then((success) {
      Navigator.pop(context);
      if (success) {
        if (status == 1) {
          AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
          // when click complete then this request remove from the list and status changes to closed..
          _gasRefillProvider?.reset();
          allRequestsProvider.getAllRequests(context, typeTransaction: 2);
        }
        Navigator.pop(context);
      }
    });
  }

  @override
  void dispose() {
    _deliveredQuantityController.dispose();
    _commentController.dispose();
    _workingHoursController.dispose();
    super.dispose();
  }

  void updateTimer({TimerModel? timer}) {
    _formModel.timer = timer;
    if (timer?.startAt != null && timer?.endAt != null) {
      _formModel.timerModelList = _formModel.timerModelList ?? [];
      _formModel.timerModelList!.add(timer!);
    }
    // notifyListeners();
  }

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    if (_firstTime) {
      String? clientName;
      if (widget.gasRefillModel != null) {
        _gasRefillProvider!.expectedDateTime = DateTime.tryParse(_formModel.expectedDate ?? "");
        _formModel.timer = TimerModel(startAt: DateTime.tryParse(widget.gasRefillModel?.startDate ?? ""), endAt: DateTime.tryParse(widget.gasRefillModel?.endDate ?? ""));
        clientName = _formModel.site?.custName;
      } else {
        _formModel.timer = null;
        clientName = _userProvider.user?.clientName;
      }
    }
    double totalWorkingHours = _formModel.gasRefillTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDate!).difference(DateTime.parse(item.startDate!)).inSeconds) ?? 0;

    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.gasRefill,
        onWillPopScope: () {
          _onSubmit(context, 0);
        },
      ),
      key: _scaffoldKey,
      body: Form(
        key: _formKey,
        child: SafeArea(
          child: LoadingManager(
              isLoading: _isLoading,
              isFailedLoading: false,
              stateCode: 200,
              onRefresh: () async {},
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        8.height,
                        SingleItemDropDownMenu<Lookup, NullableLoadingProvider>(
                          context: context,
                          title: context.translation.quantity,
                          backgroundColor: AppColor.fieldBgColor(context),
                          showShadow: false,
                          showAsBottomSheet: true,
                          initialValue: _deliveredQuantity,
                          staticData: deliveredQuantity,
                          onSelect: (value) {
                            _deliveredQuantity = value;
                            _currentDetails.deliverdQty = value!.value;
                          },
                        ),
                        8.height,
                        _timerWidget(context, totalWorkingHours),
                        8.height,
                        AppTextFormField(
                          labelText: context.translation.technicalComment,
                          textInputType: TextInputType.multiline,
                          hintStyle: TextStyle(color: context.isDark?AppColor.white10:AppColor.black10),
                          labelStyle: TextStyle(color: context.isDark?AppColor.white10:AppColor.black10),
                          alignLabelWithHint: true,
                          backgroundColor: AppColor.fieldBgColor(context),
                          showShadow: false,
                          controller: _commentController,
                          onChange: (value) {
                            _formModel.techComment = value;
                          },
                          onSaved: (value) {},
                        ),
                        16.height,
                        AttachmentPicker(
                          label: context.translation.attachFiles,
                          attachment: _attachments,
                          buttonColor: AppColor.black10,
                          onlyImages: false,
                          buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.neutral120),
                        ),
                        8.height,
                      ],
                    ).toShadowContainer(context),
                  ).expanded,
                  FooterActionButton.footerContainer(
                    context: context,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        AppFilledButton(
                          label: context.translation.save,
                          buttonColor: context.isDark?AppColor.neutral70:AppColor.white60,
                          textColor:  context.isDark?AppColor.white10:AppColor.black10,
                          onPressed: () => _onSubmit(context, 0),
                        ).expanded,
                        12.width,
                        AppFilledButton(
                          label: context.translation.complete,
                          buttonColor: AppColor.primary10,
                          onPressed: () => _onSubmit(context, 1),
                        ).expanded,
                      ],
                    ),
                  ),
                ],
              )),
        ),
      ),
    ).handlePopScope(
        cxt: context,
        onSave: () {
          _onSubmit(context, 0);
        });
  }

  Widget _timerWidget(BuildContext context, double totalWorkingHours) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        AppTimer(
          label: context.translation.workingHours,
          timer: _formModel.timer,
          pickerFromDate: DateTime.tryParse(widget.gasRefillModel?.createdDate ?? ''),
          pickerTimer: _formModel.gasRefillTimePicker,
          onPick: (time) {
            _formModel.gasRefillTimePicker = time;
          },
          width: double.infinity,
          decoration: BoxDecoration(
            color: AppColor.fieldBgColor(context),
            // color: AppColor.neutral100,
            borderRadius: BorderRadius.circular(10),
          ),
          timerProgress: (isRunning) {},
          onChange: (timer) async {
            updateTimer(timer: timer);
            return true;
          },
        ),
        if (totalWorkingHours > 0.0) ...[
          12.height,
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              'Total Working Time:'.bodyText2(context).custom(color: AppColor.neutral120),
              8.width,
              Text(
                ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round()),
                style: AppTextStyles.bodyText.copyWith(color:context.isDark?AppColor.white10: AppColor.neutral50, fontWeight: FontWeight.w600),
              ),
            ],
          ),
        ],
      ],
    );
  }
}
