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

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/asset_transfer_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/widget_extensions.dart';
import 'package:test_sa/models/device/asset_transfer.dart';
import 'package:test_sa/models/device/asset_transfer_attachment.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/providers/asset_transfer/asset_transfer_status_provider.dart';
import 'package:test_sa/views/app_style/sizing.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/lookup.dart';
import '../../../models/ppm/ppm.dart';
import '../../../new_views/app_style/app_color.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/e_signature/e_signature.dart';
import '../../widgets/timer/app_timer.dart';

class UpdateDeviceTransfer extends StatefulWidget {
  final AssetTransfer model;
  final bool isSender;

  const UpdateDeviceTransfer({Key? key, required this.model, required this.isSender}) : super(key: key);

  @override
  State<UpdateDeviceTransfer> createState() => _UpdateDeviceTransferState();
}

class _UpdateDeviceTransferState extends State<UpdateDeviceTransfer> {
  final bool _isLoading = false;
  bool _validate = false;
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  Uint8List? _signature;
  late AssetTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final AssetTransfer _formModel = AssetTransfer();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<File> _files = [];

  _update() async {
    if (widget.isSender) {
      _formModel.senderVisitTimers?.add(
        VisitTimers(
          id: 0,
          startDateTime: _formModel.tbsTimer?.startAt?.toIso8601String(),
          endDateTime: _formModel.tbsTimer?.endAt?.toIso8601String(),
          workingHours: ((_formModel.tbsTimer?.durationInSecond ?? 0) / 60 / 60),
        ),
      );
    } else {
      _formModel.receiverVisitTimers?.add(
        VisitTimers(
          id: 0,
          startDateTime: _formModel.tbsTimer?.startAt?.toIso8601String(),
          endDateTime: _formModel.tbsTimer?.endAt?.toIso8601String(),
          workingHours: ((_formModel.tbsTimer?.durationInSecond ?? 0) / 60 / 60),
        ),
      );
    }

    if (_formModel.tbsTimer?.startAt == null) {
      await Fluttertoast.showToast(msg: "Working Hours Required");
      return false;
    }
    if (_formModel.tbsTimer?.endAt == null || isTimerRunning) {
      await Fluttertoast.showToast(msg: "Please Stop The Timer");
      return false;
    }
    _validate = true;
    if (!(_formKey.currentState!.validate())) {
      setState(() {});
      return false;
    }
    _formKey.currentState!.save();

    if (widget.isSender) {
      _formModel.senderAttachments = [];
    } else {
      _formModel.receiverAttachments = [];
    }

    try {
      for (var file in _files) {
        String attachmentName = file.path;
        if (attachmentName.contains("/")) {
          attachmentName = file.path.split("/").last;
          attachmentName = "$attachmentName|${base64Encode(file.readAsBytesSync())}";
        }

        if (widget.isSender) {
          _formModel.senderAttachments!.add(AssetTransferAttachment(id: 0, attachmentName: attachmentName));
        } else {
          _formModel.receiverAttachments!.add(AssetTransferAttachment(id: 0, attachmentName: attachmentName));
        }
      }
    } catch (error) {
      print(error);
    }
    await _deviceTransferProvider.updateRequest(context, assetTransfer: _formModel, isSender: widget.isSender);
  }

  @override
  void initState() {
    _formModel.fromDetails(widget.model);

    if (widget.isSender) {
      _files = widget.model.senderAttachments?.map((e) => File(e.attachmentName!)).toList() ?? [];
    } else {
      _files = widget.model.receiverAttachments?.map((e) => File(e.attachmentName!)).toList() ?? [];
    }

    super.initState();
  }

  @override
  void dispose() {
    _requestedQuantityController.dispose();
    super.dispose();
  }

  bool isTimerRunning = false;

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _deviceTransferProvider = Provider.of<AssetTransferProvider>(context, listen: false);

    double totalWorkingHours = widget.isSender
        ? (widget.model.senderVisitTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDateTime!).difference(DateTime.parse(item.startDateTime!)).inSeconds) ?? 0)
        : (widget.model.receiverVisitTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDateTime!).difference(DateTime.parse(item.startDateTime!)).inSeconds) ?? 0);

    bool isTimerEnable = widget.isSender
        ? (!(_formModel.senderMachineStatusName?.toLowerCase().contains("close") ?? false) || !(_formModel.senderMachineStatusName?.toLowerCase().contains("complete") ?? false))
        : (!(_formModel.receiverMachineStatusName?.toLowerCase().contains("close") ?? false) || !(_formModel.receiverMachineStatusName?.toLowerCase().contains("complete") ?? false));

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.updateRequest),
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                SingleChildScrollView(
                  padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _buildCard(),
                      8.height,
                      AppTextFormField(
                        initialValue: widget.isSender ? _formModel.senderTravelingHours ?? "" : _formModel.receiverTravelingHours ?? "",
                        labelText: context.translation.travelingHours,
                        onChange: (text) {
                          widget.isSender ? _formModel.senderTravelingHours = text : _formModel.receiverTravelingHours = text;
                        },
                        onSaved: (value) {
                          widget.isSender ? _formModel.senderTravelingHours = value : _formModel.receiverTravelingHours = value;
                          //_formModel?.workingHours = double.tryParse(value);
                          //     _formModel.travelingHours = value;
                        },
                        textInputType: TextInputType.number,
                        //validator: (value) => Validator.isNumeric(value) ? null : "allow numbers only",
                      ),
                      8.height,
                      if (totalWorkingHours > 0.0) ...[
                        Container(
                          height: 50.toScreenHeight,
                          padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                            color: context.isDark ? AppColor.neutral40 : AppColor.background(context),
                            borderRadius: BorderRadius.circular(10),
                            boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                "Total Working Time",
                                style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500),
                              ),
                              Text(
                                " ${formatDuration(totalWorkingHours.round())}",
                                style: Theme.of(context).textTheme.bodyLarge,
                              ),
                            ],
                          ),
                        ),
                        8.height,
                      ],
                      AppTimer(
                        label: context.translation.workingHours,
                        timer: _formModel.tbsTimer,
                        enabled: isTimerEnable,
                        // enabled: widget.isSender ? _formModel.senderEndDate == null : (_formModel?.receiverMachineStatusName?.toLowerCase()?.contains("close") ?? false),
                        timerProgress: (isRunning) {
                          isTimerRunning = isRunning;
                        },
                        onChange: (timer) async {
                          _formModel.tbsTimer = timer;
                          return true;
                        },
                      ),
                      8.height,
                      Consumer<AssetTransferStatusProvider>(builder: (context, snapshot, _) {
                        return SingleItemDropDownMenu<Lookup, AssetTransferStatusProvider>(
                          context: context,
                          title: widget.isSender ? "Status Sender" : "Status Receiver", //,context.translation.reportStatus,
                          initialValue:
                              snapshot.items.firstWhere((element) => element.name == (widget.isSender ? _formModel.senderMachineStatusName : _formModel.receiverMachineStatusName), orElse:  null),
                          onSelect: (value) {
                            if (value?.value == 4) {
                              "Status cannot be change to ${value?.name}.".addTranslation.showToast;
                              setState(() {});
                              return;
                            }
                            if (widget.isSender) {
                              _formModel.senderMachineStatusName = value?.name;
                              _formModel.senderMachineStatusId = value?.id;
                            } else {
                              _formModel.receiverMachineStatusName = value?.name;
                              _formModel.receiverMachineStatusId = value?.id;
                            }
                            setState(() {});
                          },
                        );
                      }),
                      8.height,
                      MultiFilesPicker(label: context.translation.attachImage, files: _files),
                      8.height,
                      AppTextFormField(
                        initialValue: widget.isSender ? _formModel.senderComment ?? "" : _formModel.receiverComment ?? "",
                        labelText: context.translation.comments,
                        textInputType: TextInputType.multiline,
                        alignLabelWithHint: true,
                        onSaved: (value) {
                          widget.isSender ? _formModel.senderComment = value : _formModel.receiverComment = value;
                        },
                      ),
                      8.height,
                      ESignature(
                        title: "Signature",
                        oldSignature: widget.isSender ? widget.model.senderEngSignature : widget.model.receiverEngSignature,
                        newSignature: _signature,
                        onSaved: (signature) {
                          _signature = signature;
                          if (signature == null || signature.isEmpty) return;
                          widget.isSender
                              ? _formModel.senderEngSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}"
                              : _formModel.receiverEngSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                        },
                      ),
                    ],
                  ),
                ).expanded,
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: AppFilledButton(
                    label: context.translation.update,
                    onPressed: _update,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _buildCard() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        context.translation.transferDetails.heading5(context),
        8.height,
        '${context.translation.assetName}: ${_formModel.assetName?.cleanupWhitespace.capitalizeFirstOfEach}'.bodyText(context),
        '${context.translation.requesterName}: ${_formModel.receiverEndUserName?.cleanupWhitespace.capitalizeFirstOfEach ?? ""}'.bodyText(context),
      ],
    ).toShadowContainer(context);
  }

  String formatDuration(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int remainingSeconds = seconds % 60;

    String formattedDuration = '';
    if (hours > 0) {
      formattedDuration += '$hours hour${hours > 1 ? 's' : ''} ';
    }
    if (minutes > 0) {
      formattedDuration += '$minutes minute${minutes > 1 ? 's' : ''} ';
    }
    if (remainingSeconds > 0) {
      formattedDuration += '$remainingSeconds second${remainingSeconds > 1 ? 's' : ''} ';
    }
    if (formattedDuration.isEmpty) {
      formattedDuration = 'Less than a second';
    }

    return formattedDuration.trim();
  }
}
