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_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/widget_extensions.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/views/pages/user/gas_refill/update_gas_refill_request.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.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 '../../../widgets/requests/request_status.dart';

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

  GasRefillDetailsPage({Key? key, this.priority, this.date, required this.model}) : 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 = [];

  @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);

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.gasRefillDetails),
      key: _scaffoldKey,
      body: SafeArea(
        child: FutureBuilder(
          future: gasRefillProvider.getGasRefillObjectById(widget.model.id!),
          builder: (context, snap) {
            if (snap.connectionState == ConnectionState.waiting) {
              return const ALoading();
            } else if (snap.hasData) {
              _model = snap.data as GasRefillModel;
              _attachments = _model.gasRefillAttachments?.map((e) => File(e.attachmentName ?? '')).toList() ?? [];

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: informationCard(_model),
                  ).expanded,
                  if (_userProvider.user!.type == UsersTypes.engineer && (_model.status!.value! != 2)) ...[
                    AppFilledButton(
                      onPressed: () async {
                        await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateGasRefillRequest(gasRefillModel: _model)));
                        // getVisitData();
                      },
                      label: context.translation.updateRequest,
                    ).paddingAll(16)
                  ]
                  //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: [
                    // if (widget.priority != null)
                    //   StatusLabel(
                    //     label: widget.priority,
                    //     textColor: AppColor.getRequestStatusTextColorByName(context, widget.priority!),
                    //     backgroundColor: AppColor.getRequestStatusColorByName(context, widget.priority!),
                    //   ),
                    // 8.width,
                    StatusLabel(
                      label: gasRefillModel.status?.name ?? "",
                      textColor: AppColor.getRequestStatusTextColorByName(context, gasRefillModel.status?.name ?? ""),
                      backgroundColor: AppColor.getRequestStatusColorByName(context, gasRefillModel.status?.name ?? ""),
                    ),
                  ],
                ),
                8.height,
                context.translation.callDetails.heading6(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                infoText(label: context.translation.requestNo, value: gasRefillModel.gasRefillNo),
                infoText(label: context.translation.createdBy, value: gasRefillModel.name),
                infoText(label: context.translation.gasType, value: gasRefillModel.gasRefillDetails?[0].gasType?.name),
                infoText(label: context.translation.cylinderType, value: gasRefillModel.gasRefillDetails?[0].cylinderType?.name),
                infoText(label: context.translation.cylinderSize, value: gasRefillModel.gasRefillDetails?[0].cylinderSize?.name),
                infoText(label: context.translation.site, value: gasRefillModel.site?.name?.cleanupWhitespace.capitalizeFirstOfEach),
                infoText(label: context.translation.building, value: gasRefillModel.building?.name),
                infoText(label: context.translation.floor, value: gasRefillModel.floor?.name),
                infoText(label: context.translation.department, value: gasRefillModel.department?.name),
                infoText(label: context.translation.requestedQuantity, value: gasRefillModel.gasRefillDetails?[0].requestedQty.toString()),
                _contactPersonInfo(),
                if (gasRefillModel.gasRefillDetails?[0].deliverdQty != null) ...[
                  const Divider().defaultStyle(context),
                  context.translation.workOrderDetails.heading6(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                  infoText(label: context.translation.deliveredQuantity, value: gasRefillModel.gasRefillDetails![0].deliverdQty.toString()),
                ],
                if (gasRefillModel.techComment?.isNotEmpty ?? false) infoText(label: context.translation.technicalComment, value: gasRefillModel.techComment),
                8.height,
                if (gasRefillModel.comment?.isNotEmpty ?? false) ...[
                  const Divider().defaultStyle(context),
                  Text(
                    "Comments".addTranslation,
                    style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                  ),
                  gasRefillModel.comment!.bodyText(context),
                  8.height,
                ],
                // if (gasRefillModel.techComment?.isNotEmpty ?? false) ...[
                //   const Divider().defaultStyle(context),
                //   Text(
                //     "Technical Comments".addTranslation,
                //     style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                //   ),
                //   gasRefillModel.techComment!.bodyText(context),
                //   8.height,
                // ],
                if (_attachments.isNotEmpty) ...[
                  const Divider().defaultStyle(context),
                  Text(
                    "Attachments".addTranslation,
                    style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                  ),
                  8.height,
                  FilesList(images: _model.gasRefillAttachments?.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []),
                ],
              ],
            ).expanded,
            if (_userProvider.user!.type == UsersTypes.engineer && (gasRefillModel.status?.value ?? 0) != 2) 8.height,
            Text(
              (widget.date ?? gasRefillModel.expectedDate)?.toServiceRequestCardFormat ?? "",
              textAlign: TextAlign.end,
              style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
            ),
          ],
        ).paddingOnly(top: 16, start: 16, end: 16),
      ],
    ).toShadowContainer(context, padding: 0);
  }

  Widget _contactPersonInfo() {
    if (_model.gasRefillContactPerson != null && _model.gasRefillContactPerson!.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Divider().defaultStyle(context),
          Text(
            "Contact Info".addTranslation,
            style: AppTextStyles.heading6.copyWith(
              color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
            ),
          ),
          ..._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: [
                const SizedBox(height: 8),
                infoText(label: context.translation.employeeId, value: person.employeeCode),
                infoText(label: context.translation.name, value: person.name),
                infoText(label: context.translation.email, value: person.email),
                infoText(label: context.translation.phoneNumber, value: person.mobilePhone),
                infoText(label: context.translation.extensionNo, value: person.extension),
                if (!isLast && _model.gasRefillContactPerson!.length > 1) const Divider().defaultStyle(context),
              ],
            );
          }).toList(),
        ],
      );
    }
    return const SizedBox();
  }

  Widget infoText({
    String? label,
    String? value,
  }) {
    if (value == null || value.isEmpty || value.toLowerCase() == 'null') {
      return const SizedBox();
    } else {
      return '$label: $value'.bodyText(context);
    }
  }
}
