import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_provider.dart';
import 'package:test_sa/controllers/providers/api/gas_refill_comments.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/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/new_models/gas_refill_model.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/cx_module/chat/chat_widget.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/views/widgets/bottom_sheets/rejection_reason_bottom_sheet.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

import '../../../../extensions/text_extensions.dart';
import '../../../../models/enums/user_types.dart';
import '../../../../models/new_models/gas_refill_model.dart';
import '../../../../new_views/app_style/app_color.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';
import 'update_gas_refill_request.dart';

class GasRefillDetailsPage extends StatefulWidget {
  GasRefillModel model;
  String? priority, date;
  final int moduleId;

  GasRefillDetailsPage({Key? key, this.priority, this.date, required this.model, required this.moduleId}) : super(key: key);

  @override
  State<GasRefillDetailsPage> createState() => _GasRefillDetailsPageState();
}

class _GasRefillDetailsPageState extends State<GasRefillDetailsPage> {
  GasRefillModel _model = GasRefillModel(gasRefillDetails: []);
  late UserProvider _userProvider;
  late GasRefillProvider gasRefillProvider;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<File> _attachments = [];
  bool isDataUpdated = false;

  @override
  void initState() {
    // _model.fromGasRefillModel(gasRefillModel);
    super.initState();
    Provider.of<GasRefillCommentsProvider>(context, listen: false).reset();
  }

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    gasRefillProvider = Provider.of<GasRefillProvider>(context, listen: false);

    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.gasRefillDetails,
        actions: [
          if (context.userProvider.isEngineer || context.userProvider.isNurse)
            Selector<GasRefillProvider, GasRefillModel?>(
                selector: (_, myModel) => myModel.gasRefillModel, // Selects only the userName
                builder: (_, _gasRefillModel, __) {
                  if (_gasRefillModel == null) return const SizedBox();

                  return ChatWidget(
                    moduleId: widget.moduleId,
                    isShow: context.settingProvider.isUserFlowMedical && _gasRefillModel.status!.value! != 0,
                    isReadOnly: _gasRefillModel.status!.value! != 1,
                    requestId: widget.model.id!.toInt(),
                    assigneeEmployeeNumber: _gasRefillModel.assignedEmployee?.employeeId!,
                    myLoginUserID: context.userProvider.user!.employeeId ?? context.userProvider.user!.username!,
                    contactEmployeeINumber: _gasRefillModel.gasRefillContactPerson!.first.employeeCode!,
                  );
                })
        ],
      ),
      key: _scaffoldKey,
      body: FutureBuilder(
        future: gasRefillProvider.getGasRefillObjectById(widget.model.id!, refresh: isDataUpdated),
        builder: (context, snap) {
          if (snap.connectionState == ConnectionState.waiting) {
            return const ALoading();
          } else if (snap.hasData) {
            _model = snap.data as GasRefillModel;
            _attachments = _model.gasRefillAttachments?.whereType<GenericAttachmentModel>().map((e) => File(e.name ?? '')).toList() ?? [];
            isDataUpdated = false;
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: informationCard(_model),
                ).expanded,
                if (context.settingProvider.isUserFlowMedical && _userProvider.user!.type == UsersTypes.engineer && (_model.status!.value! == 0))
                  FooterActionButton.footerContainer(
                    context: context,
                    child: AppFilledButton(
                      onPressed: () async {
                        Utils.showLoading(context);
                        await gasRefillProvider.assignEngineerToHimself(_model.id!.toInt());
                        isDataUpdated = true;
                        Utils.hideLoading(context);
                        setState(() {});
                      },
                      label: 'Assign To Me',
                    ),
                  )
                else
                  if (_userProvider.user!.type == UsersTypes.engineer && (_model.status!.value! == 1)) ...[
                    FooterActionButton.footerContainer(
                      context: context,
                      child: Row(
                        children: [
                          AppFilledButton(
                            label: context.translation.cancel,
                            buttonColor: AppColor.white60,
                            textColor: AppColor.black10,
                            loading: false,
                            onPressed: () async {
                              context.showBottomSheet(
                                  RejectionReasonBottomSheet(
                                    onRejectPressed: (int reasonId, String comment) async {
                                      await Future.delayed(const Duration(milliseconds: 500));
                                      var data = await gasRefillProvider.engineerReject({"gasRefillId": _model.id!.toInt(), "rejectReasonId": reasonId, "rejectComment": comment});
                                      isDataUpdated = data != null;
                                      return isDataUpdated;
                                    },
                                    onRefreshed: () {
                                      setState(() {});
                                    },
                                  ),
                                  title: "Rejection Reason".addTranslation);
                            },
                          ).expanded,
                          16.width,
                          AppFilledButton(
                            onPressed: () async {
                              bool? isRefresh = await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateGasRefillRequest(gasRefillModel: _model)));
                              ;
                              if (isRefresh != null && isRefresh) {
                                isDataUpdated = false;
                                setState(() {});
                              }
                              // getVisitData();
                            },
                            label: context.translation.updateRequest,
                          ).expanded,
                        ],
                      ),
                    )
                  ]
                //TODO need to uncomment this to enable nurse edit gas refill request.
                // else if (_model.status!.value! == 0) ...[
                //   AppFilledButton(
                //     onPressed: () async {
                //       await Navigator.of(context).push(MaterialPageRoute(
                //           builder: (_) => GasRefillRequestForm(
                //                 gasModel: _model,
                //                 gasRefillDetails: _model.gasRefillDetails?[0],
                //               )));
                //       // getVisitData();
                //     },
                //     label: context.translation.updateRequest,
                //   ).paddingAll(16)
                // ],
              ],
            );
          }
          return NoDataFound(message: context.translation.noDataFound).center;
        },
      ),
    );
  }

  Widget informationCard(GasRefillModel gasRefillModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    StatusLabel(
                      label: gasRefillModel.status?.name ?? "",
                      textColor: AppColor.getRequestStatusTextColorByName(context, gasRefillModel.status?.name ?? ""),
                      backgroundColor: AppColor.getRequestStatusColorByName(context, gasRefillModel.status?.name ?? ""),
                    ),
                  ],
                ),
                8.height,
                InfoHeader16Widget(context.translation.callDetails),
                InfoTextWidget(label: context.translation.requestNo, value: gasRefillModel.gasRefillNo ?? '-', copyValue: true),
                InfoTextWidget(label: context.translation.createdBy, value: gasRefillModel.name ?? '-'),
                InfoTextWidget(label: context.translation.gasType, value: gasRefillModel.gasRefillDetails?[0].gasType?.name ?? '-'),
                InfoTextWidget(label: context.translation.cylinderType, value: gasRefillModel.gasRefillDetails?[0].cylinderType?.name ?? '-'),
                InfoTextWidget(label: context.translation.cylinderSize, value: gasRefillModel.gasRefillDetails?[0].cylinderSize?.name ?? '-'),
                InfoTextWidget(label: context.translation.site, value: gasRefillModel.site?.name?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'),
                InfoTextWidget(label: context.translation.building, value: gasRefillModel.building?.name ?? '-'),
                InfoTextWidget(label: context.translation.floor, value: gasRefillModel.floor?.name ?? '-'),
                InfoTextWidget(label: context.translation.department, value: gasRefillModel.department?.name ?? '-'),
                InfoTextWidget(label: context.translation.requestedQuantity, value: gasRefillModel.gasRefillDetails?[0].requestedQty?.toString() ?? '-'),
                _contactPersonInfo(),
                if (gasRefillModel.gasRefillDetails?[0].deliverdQty != null) ...[
                  const Divider().defaultStyle(context),
                  InfoHeader16Widget(context.translation.workOrderDetails),
                  InfoTextWidget(label: context.translation.deliveredQuantity, value: gasRefillModel.gasRefillDetails![0].deliverdQty?.toString() ?? '-'),
                ],
                if (gasRefillModel.techComment?.isNotEmpty ?? false)
                  InfoTextWidget(label: context.translation.technicalComment, value: gasRefillModel.techComment ?? '-'),
                if (gasRefillModel.comment?.isNotEmpty ?? false) ...[
                  const Divider().defaultStyle(context),
                  InfoHeader16Widget("Comments".addTranslation),
                  Text(
                    gasRefillModel.comment ?? '',
                    style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)),
                  ),
                ],
                if (_attachments.isNotEmpty) ...[
                  const Divider().defaultStyle(context),
                  InfoHeader16Widget("Attachments".addTranslation),
                  FilesList(images: _model.gasRefillAttachments?.whereType<GenericAttachmentModel>().where((e) => e.name != null).map((e) => URLs.getFileUrl(e.name!) ?? '').toList() ?? []),
                ],
              ],
            ).expanded,
            InfoDateWidget((widget.date ?? gasRefillModel.expectedDate)?.toString() ?? ""),
          ],
        ),
      ],
    ).toShadowContainer(context, padding: 16);
  }

  Widget _contactPersonInfo() {
    if (_model.gasRefillContactPerson != null && _model.gasRefillContactPerson!.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Divider().defaultStyle(context),
          InfoHeader16Widget("Contact Info".addTranslation),
          ..._model.gasRefillContactPerson!.asMap().entries.map((entry) {
            final index = entry.key;
            final person = entry.value;
            final isLast = index == _model.gasRefillContactPerson!.length - 1;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InfoTextWidget(label: context.translation.employeeId, value: person.employeeCode ?? '-'),
                InfoTextWidget(label: context.translation.name, value: person.name ?? '-'),
                InfoTextWidget(label: context.translation.email, value: person.email ?? '-'),
                InfoTextWidget(label: context.translation.phoneNumber, value: person.mobilePhone ?? '-'),
                InfoTextWidget(label: context.translation.extensionNo, value: person.extension ?? '-'),
                if (!isLast && _model.gasRefillContactPerson!.length > 1) const Divider().defaultStyle(context),
              ],
            );
          }).toList(),
        ],
      );
    }
    return const SizedBox();
  }

}