import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_provider.dart';
import 'package:test_sa/controllers/api_routes/urls.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/models/device/device_transfer.dart';
import 'package:test_sa/views/pages/device_transfer/update_device_transfer.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/loading_manager.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import '../../../extensions/text_extensions.dart';
import '../../../models/enums/user_types.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 DeviceTransferDetails extends StatefulWidget {
  final DeviceTransfer model;

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

  @override
  State<DeviceTransferDetails> createState() => _DeviceTransferDetailsState();
}

class _DeviceTransferDetailsState extends State<DeviceTransferDetails> {
  UserProvider? _userProvider;
  DeviceTransfer? _model;
  final bool _isLoading = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  List<File> _attachments = [];
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

  @override
  Widget build(BuildContext context) {
    _userProvider ??= Provider.of<UserProvider>(context);

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.transferDetails),
      key: _scaffoldKey,
      body: SafeArea(
        child: FutureBuilder(
          future: Provider.of<DeviceTransferProvider>(context).getRequestById(assetTransferId: widget.model.id?.toInt()),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const ALoading();
            } else {
              _model = snapshot.data as DeviceTransfer?;
              _attachments = _model?.assetTransferAttachments?.map((e) => File(e.attachmentName ?? '')).toList() ?? [];
              return _model != null
                  ? Form(
                      key: _formKey,
                      child: LoadingManager(
                        isLoading: _isLoading,
                        isFailedLoading: false,
                        stateCode: 200,
                        onRefresh: () async {},
                        child: SingleChildScrollView(
                          child: Column(
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    children: [
                                      StatusLabel(
                                        label: _model?.transferType?.name,
                                        id: _model?.transferType?.id?.toInt(),
                                        textColor: AppColor.getRequestStatusTextColorByName(context, _model?.transferType?.name),
                                        backgroundColor: AppColor.getRequestStatusColorByName(context, _model?.transferType?.name),
                                      ),
                                      Text(
                                        _model?.createdOn != null ? _model!.createdOn!.toServiceRequestCardFormat : "",
                                        textAlign: TextAlign.end,
                                        style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                                      ),
                                    ],
                                  ),
                                  8.height,
                                  context.translation.callDetails.heading6(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                                  _buildTextWidget('${context.translation.trNumber} : ${_model?.transferCode ?? "-"}'),
                                  _buildTextWidget('${context.translation.createdBy} : ${_model?.name ?? "-"}'),
                                  const Divider().defaultStyle(context),
                                  context.translation.assetInformation.heading6(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                                  _buildTextWidget('${context.translation.assetName} : ${_model?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? ""}'),
                                  _buildTextWidget('${context.translation.assetNumber} : ${_model?.assetNumber ?? "-"}'),
                                  _buildTextWidget('${context.translation.model} : ${_model?.modelName ?? "-"}'),
                                  _buildTextWidget('${context.translation.sn} : ${_model?.assetSerialNo ?? "-"}'),
                                  _buildTextWidget('${context.translation.site} : ${_model?.senderSiteName ?? "-"}'),
                                  _buildTextWidget('${context.translation.building} : ${_model?.senderBuildingName ?? "-"}'),
                                  _buildTextWidget('${context.translation.floor} : ${_model?.senderFloorName ?? "-"}'),
                                  _buildTextWidget('${context.translation.department} : ${_model?.senderDepartmentName ?? "-"}'),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      _contactPersonInfo(),
                                      if ((_model?.comment ?? "").isNotEmpty) ...[
                                        const Divider().defaultStyle(context),
                                        context.translation.callComments.heading6(context).custom(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
                                        8.height,
                                        _buildTextWidget(_model!.comment!),
                                      ],
                                      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?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []),
                                        //attachmentWidget(),
                                      ]
                                    ],
                                  ),
                                ],
                              ).toShadowContainer(context),
                              8.height,
                              if (_model?.transferType?.value == 1) ...[
                                _internalRequestDetailsCard()
                              ] else ...[
                                // sender card
                                _buildCard(
                                  isSender: true,
                                  site: _model?.senderSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  dept: _model?.senderDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  building: _model?.senderBuildingName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  floor: _model?.senderFloorName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  assignTo: _model?.senderAssignedEmployeeName,
                                  comment: _model?.senderComment ?? "",
                                  statusLabel: _model?.senderMachineStatusName != null
                                      ? StatusLabel(
                                          label: _model!.senderMachineStatusName!,
                                          id: _model!.senderMachineStatusId!.toInt(),
                                          textColor: AppColor.getRequestStatusTextColorByName(context, _model!.senderMachineStatusName!),
                                          backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.senderMachineStatusName!),
                                        )
                                      : null,
                                ),
                                8.height,
                                // receiver card
                                _buildCard(
                                  isSender: false,
                                  site: _model?.destSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  dept: _model?.destDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  building: _model?.destBuildingName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  floor: _model?.destFloorName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  assignTo: _model?.receiverAssignedEmployeeName,
                                  comment: _model?.receiverComment ?? "",
                                  statusLabel: _model?.receiverMachineStatusName != null
                                      ? StatusLabel(
                                          label: _model!.receiverMachineStatusName ?? "",
                                          id: _model!.receiverMachineStatusId!.toInt(),
                                          textColor: AppColor.getRequestStatusTextColorByName(context, _model!.receiverMachineStatusName!),
                                          backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.receiverMachineStatusName!))
                                      : null,
                                ),
                              ],
                            ],
                          ).paddingAll(16),
                        ),
                      ),
                    )
                  : const Center(
                      child: NoDataFound(),
                    );
            }
          },
        ),
      ),
    );
  }

  _buildTextWidget(String text) {
    return text.bodyText(context);
  }

  _internalRequestDetailsCard() {
    bool isCurrentEngineerEligibleForEdit = _model?.senderAssignedEmployeeId == _userProvider!.user?.userID;
    bool isCurrentRequestEditAble = (!(_model?.senderMachineStatusValue == 3));
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    StatusLabel(
                      label: _model!.senderMachineStatusName!,
                      id: _model!.senderMachineStatusId!.toInt(),
                      textColor: AppColor.getRequestStatusTextColorByName(context, _model!.senderMachineStatusName!),
                      backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.senderMachineStatusName!),
                    ),
                    // 8.width,
                    // StatusLabel(
                    //   label: _model?.transferType?.name,
                    //   id: _model?.transferType?.id?.toInt(),
                    //   textColor: AppColor.getRequestStatusTextColorByName(context, _model?.transferType?.name),
                    //   backgroundColor: AppColor.getRequestStatusColorByName(context, _model?.transferType?.name),
                    // )
                  ],
                ),
              ],
            ),
            if ((_userProvider!.user?.type == UsersTypes.engineer))
              if (isCurrentEngineerEligibleForEdit && isCurrentRequestEditAble)
                "edit".toSvgAsset(height: 40, width: 40).onPress(() async {
                  bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: true)))) as bool;
                  if (isReload ?? false) {
                    setState(() {});
                  }
                }),
          ],
        ),
        8.height,
        context.translation.workOrderDetails.heading5(context),
        infoText(label: context.translation.destinationSite, value: _model?.senderSiteName),
        // infoText(label: "Sender Building".addTranslation, value: _model?.senderBuildingName),
        // infoText(label: "Sender Floor".addTranslation, value: _model?.senderFloorName),
        // infoText(label: "Sender Department".addTranslation, value: _model?.senderDepartmentName),
        infoText(label: "Building".addTranslation, value: _model?.destBuildingName),
        infoText(label: "Floor".addTranslation, value: _model?.destFloorName),
        infoText(label: "Department".addTranslation, value: _model?.destDepartmentName),
        if (_model!.senderComment != null && _model!.senderComment!.isNotEmpty) ...[
          8.height,
          const Divider().defaultStyle(context),
          Text(
            "Technical Comments".addTranslation,
            style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
          ),
          _buildTextWidget(_model?.senderComment ?? ''),
        ]
      ],
    ).toShadowContainer(context);
  }

  _buildCard({required String site, String? building, String? dept, String? floor, required String comment, required bool isSender, StatusLabel? statusLabel, String? assignTo}) {
    bool isCurrentEngineerEligibleForEdit = isSender ? _model?.senderAssignedEmployeeId == _userProvider!.user?.userID : _model?.receiverAssignedEmployeeId == _userProvider!.user?.userID;

    bool isCurrentRequestClosed = isSender ? ((_model?.senderMachineStatusValue == 3)) : ((_model?.receiverMachineStatusValue == 3));
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                statusLabel ?? Container(),
                if (statusLabel != null) 8.height,
                isSender ? context.translation.senderDetails.heading5(context) : context.translation.receiverDetails.heading5(context),
              ],
            ),
            if ((_userProvider!.user?.type == UsersTypes.engineer))
              if (isCurrentEngineerEligibleForEdit && !isCurrentRequestClosed)

                // if (isSender
                //     ? (!(_model?.senderMachineStatusName?.toLowerCase()?.contains("close") ?? false) && !(_model?.senderMachineStatusName?.toLowerCase()?.contains("complete") ?? false))
                //     : (!(_model?.receiverMachineStatusName?.toLowerCase()?.contains("close") ?? false) && !(_model?.receiverMachineStatusName?.toLowerCase()?.contains("complete") ?? false)))
                //
                 "edit".toSvgAsset(height: 48, width: 48).onPress(() async {
                  bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: isSender)))) as bool;
                  if (isReload ?? false) {
                    setState(() {});
                  }
                }),
          ],
        ),
        infoText(label: context.translation.site, value: site),
        infoText(label: context.translation.building, value: building),
        infoText(label: context.translation.floor, value: floor),
        infoText(label: context.translation.department, value: dept),
        infoText(label: context.translation.assignedTo, value: assignTo),
        if (comment.isNotEmpty) ...[
          8.height,
          const Divider().defaultStyle(context),
          Text(
            "Technical Comments".addTranslation,
            style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
          ),
          _buildTextWidget(comment),
        ]
      ],
    ).toShadowContainer(context);
  }

  Widget _contactPersonInfo() {
    if (_model?.assetTransferContactPersons != null && _model!.assetTransferContactPersons!.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!.assetTransferContactPersons!.asMap().entries.map((entry) {
            final index = entry.key;
            final person = entry.value;
            final isLast = index == _model!.assetTransferContactPersons!.length - 1;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 8),
                infoText(label: context.translation.employeeId, value: person.employeeNumber),
                infoText(label: context.translation.name, value: person.employeeName),
                infoText(label: context.translation.email, value: person.email),
                infoText(label: context.translation.phoneNumber, value: person.mobileNo),
                infoText(label: context.translation.extensionNo, value: person.extension),
                if (!isLast && _model!.assetTransferContactPersons!.length > 1) const Divider().defaultStyle(context),
              ],
            );
          }).toList(),
        ],
      );
    }
    return const SizedBox();
  }

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