import 'dart:convert';
import 'dart:developer';
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/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/generic_attachment_model.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart';
import 'package:test_sa/modules/internal_audit_module/models/update_audit_form_model.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.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/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/working_time_tile.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';
import 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.dart';

class UpdateSystemInternalAuditPage extends StatefulWidget {
  static const String id = "update-system-internal-audit";
  SystemInternalAuditDataModel? model;

  UpdateSystemInternalAuditPage({Key? key, this.model}) : super(key: key);

  @override
  State<UpdateSystemInternalAuditPage> createState() => _UpdateSystemInternalAuditPageState();
}

class _UpdateSystemInternalAuditPageState extends State<UpdateSystemInternalAuditPage> {
  final bool _isLoading = false;
  double totalWorkingHours = 0.0;
  AuditFormModel formModel = AuditFormModel();
  final TextEditingController _workingHoursController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<GenericAttachmentModel> _attachments = [];

  //TODO need to check if it's needed or not..
  List<TimerHistoryModel> timerList = [];

  @override
  void initState() {
    populateForm();
    super.initState();
  }

  void populateForm() {
    formModel.requestId = widget.model?.id;
    formModel.id = widget.model?.id;
    formModel.debrief = widget.model?.engineerData?.debrief;
    _attachments = widget.model?.engineerData?.attachments?.whereType<GenericAttachmentModel>().map((e) => GenericAttachmentModel(id: e.id?.toInt() ?? 0, name: e.name ?? '')).toList() ?? [];

    calculateWorkingTime();
  }

  void calculateWorkingTime() {
    final helperModel = formModel;
    final timers = helperModel.auditTimers ?? [];
    totalWorkingHours = timers.fold<double>(0.0, (sum, item) {
      if (item.startDate == null || item.endDate == null) return sum;
      try {
        final start = DateTime.parse(item.startDate!);
        final end = DateTime.parse(item.endDate!);
        final diffInHours = end.difference(start).inSeconds / 3600.0; // convert to hours
        return sum + diffInHours;
      } catch (_) {
        return sum;
      }
    });
    timerList = timers.map((e) {
      return TimerHistoryModel(
        id: e.id,
        startTime: e.startDate,
        endTime: e.endDate,
        workingHours: e.startDate,
      );
    }).toList();
  }

  _onSubmit(BuildContext context) async {
    /// Need to refactor this code when timer requirements clear keep picker or both.
    //    // formModel.auditTimers ??= [];
    //     // if (formModel.auditTimePicker != null) {
    //     //   int durationInSecond = formModel.auditTimePicker!.endAt!.difference(formModel.auditTimePicker!.startAt!).inSeconds;
    //     //   formModel.auditTimers?.add(
    //     //     InternalAuditTimerModel(
    //     //       id: 0,
    //     //       startDate: formModel.auditTimePicker!.startAt!.toIso8601String(), // Handle potential null
    //     //       endDate: formModel.auditTimePicker!.endAt?.toIso8601String(), // Handle potential null
    //     //       // endDate: formModel.auditTimePicker!.startAt?.add(const Duration(hours: 1)).toIso8601String(), // Handle potential null
    //     //       totalWorkingHour: ((durationInSecond) / 60 / 60),
    //     //     ),
    //     //   );
    //     // }
    //     // formModel.timerModelList?.forEach((timer) {
    //     //   int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
    //     //   formModel.auditTimers?.add(
    //     //     InternalAuditTimerModel(
    //     //       id: 0,
    //     //       startDate: timer.startAt!.toIso8601String(), // Handle potential null
    //     //       endDate: timer.endAt?.toIso8601String(), // Handle potential null
    //     //       totalWorkingHour: ((durationInSecond) / 60 / 60),
    //     //     ),
    //     //   );
    //     // });
    bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;
    InternalAuditProvider provider = Provider.of<InternalAuditProvider>(context, listen: false);
    if (formModel.startTime == null) {
      Fluttertoast.showToast(msg: "Working Hours Required");
      return;
    }
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());

    _formKey.currentState!.save();
    formModel.attachments = [];
    for (var item in _attachments) {
      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name?.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
      formModel.attachments!.add(
        GenericAttachmentModel(
          id: item.id,
          documentType: item.documentType,
          // originalName: fileName,
          name: fileName,
        ),
      );
    }
    final success = await provider.updateSystemInternalAudit(model: formModel);
    Navigator.pop(context);
    if (success) {
      Navigator.of(context).pop(true);
    } else {
      Fluttertoast.showToast(msg: 'Failed to update');
    }
  }

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

  void updateTimer({TimerModel? timer}) {
    if (timer?.startAt != null && timer?.endAt != null) {
      final start = timer!.startAt!;
      final end = timer.endAt!;

      final difference = end.difference(start);
      final totalHours = difference.inSeconds / 3600.0;
      formModel.startTime = start;
      formModel.endTime = end;
      formModel.totalHours = totalHours;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: 'Update Information'.addTranslation,
        onWillPopScope: () {
          formModel.isComplete = false;
          _onSubmit(context);
        },
      ),
      key: _scaffoldKey,
      body: Form(
        key: _formKey,
        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,
                      AppTextFormField(
                        labelText: 'Debrief'.addTranslation,
                        textInputType: TextInputType.multiline,
                        hintStyle: TextStyle(color: context.isDark ? AppColor.white10 : AppColor.black10),
                        labelStyle: TextStyle(color: context.isDark ? AppColor.white10 : AppColor.black10),
                        alignLabelWithHint: true,
                        initialValue: formModel.debrief,
                        backgroundColor: AppColor.fieldBgColor(context),
                        showShadow: false,
                        onSaved: (value) {
                          formModel.debrief = value;
                        },
                      ),
                      8.height,
                      _timerWidget(context, totalWorkingHours),
                      16.height,
                      AttachmentPicker(
                        label: 'Upload Attachment',
                        showAsListView: true,
                        attachment: _attachments,
                        buttonColor: AppColor.primary10,
                        onlyImages: false,
                        buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                      ),
                      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: () {
                            formModel.isComplete = false;
                            _onSubmit(context);
                          }).expanded,
                      12.width,
                      AppFilledButton(
                          label: context.translation.complete,
                          buttonColor: AppColor.primary10,
                          onPressed: () {
                            formModel.isComplete = true;
                            _onSubmit(context);
                          }).expanded,
                    ],
                  ),
                ),
              ],
            )),
      ),
    ).handlePopScope(
        cxt: context,
        onSave: () {
          formModel.isComplete = false;
          _onSubmit(context);
        });
  }

  Widget _timerWidget(BuildContext context, double totalWorkingHours) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        ///this is for  multiple timers...
        // AppTimer(
        //   label: context.translation.timer,
        //   timer: formModel.auditTimerModel,
        //   // enabled: enableTimer,
        //   pickerTimer: formModel.auditTimePicker,
        //   pickerFromDate: DateTime.tryParse(widget.model?.createdDate ?? ''),
        //   onPick: (time) {
        //     formModel.auditTimePicker = time;
        //   },
        //   timerProgress: (isRunning) {},
        //   onChange: (timer) async {
        //     formModel.auditTimerModel = timer;
        //     if (timer.startAt != null && timer.endAt != null) {
        //       formModel.timerModelList = formModel.timerModelList ?? [];
        //       formModel.timerModelList!.add(timer);
        //     }
        //     return true;
        //   },
        // ),
        AppTimer(
          label: context.translation.workingHours,
          showTimer: false,
          timer: formModel.auditTimerModel,
          // enabled:formModel.endTime==null,
          pickerFromDate: DateTime.tryParse(widget.model?.createdDate ?? ''),
          pickerTimer: formModel.auditTimePicker,
          onPick: (time) {
            updateTimer(timer: time);
          },
          width: double.infinity,
          decoration: BoxDecoration(
            color: AppColor.fieldBgColor(context),
            borderRadius: BorderRadius.circular(10),
          ),
          timerProgress: (isRunning) {},
          onChange: (timer) async {
            updateTimer(timer: timer);
            log('here onChange ${timer.startAt}');

            return true;
          },
        ),
        if (totalWorkingHours > 0.0) ...[
          12.height,
          WorkingTimeTile(
            timerList: timerList,
            totalWorkingTime: totalWorkingHours,
          ),
        ],
      ],
    );
  }
}
