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

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/helper/utils.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/loan_module/models/loan_form_model.dart';
import 'package:test_sa/modules/loan_module/models/loan_installation_pullout_form_model.dart';
import 'package:test_sa/modules/loan_module/models/loan_request_model.dart';
import 'package:test_sa/modules/loan_module/provider/loan_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_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.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 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';

class InstallationFormView extends StatefulWidget {
  LoanRequestModel? loanData;
  bool isInstallation;

  InstallationFormView({Key? key, this.loanData, this.isInstallation = true}) : super(key: key);

  @override
  _InstallationFormViewState createState() {
    return _InstallationFormViewState();
  }
}

class _InstallationFormViewState extends State<InstallationFormView> {
  final _formKey = GlobalKey<FormState>();
  List<GenericAttachmentModel> _attachments = [];

  final LoanInstallationPullOutFormModel _formData = LoanInstallationPullOutFormModel();

  @override
  void initState() {
    super.initState();
    _formData.loanId = widget.loanData?.id;
  }

  @override
  void 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;
      _formData.startTime = start;
      _formData.endTime = end;
      _formData.totalHours = totalHours;
    }

    if (timer == null) {
      _formData.startTime = null;
      _formData.endTime = null;
      _formData.totalHours = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(title: 'Installation Report'.addTranslation),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (widget.isInstallation) ...[
                    AppTextFormField(
                      initialValue: "",
                      labelText: "Updates SN",
                      validator: (value) {
                        if ((value ?? "").isEmpty) return "Mandatory";
                        return null;
                      },
                      style: Theme.of(context).textTheme.titleMedium,
                      backgroundColor: AppColor.fieldBgColor(context),
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      showShadow: false,
                      textInputType: TextInputType.text,
                      textInputAction: TextInputAction.next,
                      onChange: (value) {
                        _formData.snNo = value;
                      },
                    ),
                    8.height,
                  ],
                  ADatePicker(
                    label: widget.isInstallation ? "Installation Date".addTranslation : "Validation Date".addTranslation,
                    hideShadow: true,
                    backgroundColor: AppColor.fieldBgColor(context),
                    to: DateTime.now().add(const Duration(days: 365)),
                    formatDateWithTime: true,
                    date: _formData.date,
                    onDatePicker: (DateTime date) async {
                      final time = await showThemedTimePicker(context: context, initialTime: TimeOfDay.now());
                      if (time == null) return;
                      setState(() {
                        _formData.date = DateTime(date.year, date.month, date.day, time.hour, time.minute);
                      });
                    },
                  ),
                  8.height,
                  AppTimer(
                    label: context.translation.workingHours,
                    timer: _formData.timerModel,
                    // pickerFromDate: DateTime.tryParse(widget.createdDate ?? ''),
                    pickerFromDate: DateTime(DateTime.now().year, DateTime.now().month, 1),
                    pickerTimer: _formData.timerModel,
                    showTimer: false,
                    onPick: (timer) {
                      updateTimer(timer: timer);
                    },
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColor.fieldBgColor(context),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    timerProgress: (isRunning) {},
                    onChange: (timer) async {
                      updateTimer(timer: timer);
                      return true;
                    },
                  ),
                  ESignature(
                    title: 'End-user signature'.addTranslation,
                    backgroundColor: AppColor.fieldBgColor(context),
                    showShadow: false,
                    oldSignature: '',
                    newSignature: _formData.signature,
                    onChange: (Uint8List signature) {
                      if (signature.isEmpty) return;
                      setState(() {
                        _formData.signature = signature;
                      });
                    },
                  ),
                  24.height,
                  "Attachments".bodyText(context).custom(color: AppColor.black10),
                  8.height,
                  AttachmentPicker(
                    label: context.translation.attachments,
                    attachment: _attachments,
                    buttonColor: AppColor.primary10,
                    onlyImages: false,
                    showAsListView: true,
                    buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                    onChange: (attachments) {
                      _attachments = attachments;
                      setState(() {});
                    },
                  ),
                ],
              ).toShadowContainer(context, borderRadius: 20),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(
                buttonColor: AppColor.primary10,
                label: context.translation.submitRequest,
                onPressed: _submitForm,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;
    if (_formData.date == null) {
      "Please select installation date".showToast;
      return;
    }
    if (_formData.startTime == null || _formData.endTime == null) {
      "Please select start and end time".showToast;
      return;
    }
    if (_formData.signature == null || _formData.signature!.isEmpty) {
      "Signature is required".showToast;
      return;
    }

    _formData.loanAttachment = [];

    for (var item in _attachments) {
      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
      _formData.loanAttachment!.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: widget.loanData?.id, documentType: item.documentType));
    }
    Utils.showLoading(context);
    _formData.loanStatusId = widget.loanData?.loanStatusValue;
    _formData.userId = context.userProvider.user?.userID;
    LoanProvider incidentProvider = Provider.of<LoanProvider>(context, listen: false);
    bool isSuccess = await incidentProvider.loanWorkflowAction(_formData.toInstallationJson());
    Utils.hideLoading(context);
    if (isSuccess) {
      Navigator.pop(context, true);
    }
  }
}
