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

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/device/asset_transfer_attachment.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/service_request/pending_service_request_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/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/providers/ppm_service_provider.dart';
import 'package:test_sa/views/pages/user/requests/pending_requests_screen.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

import '../../../models/new_models/building.dart';
import '../../../models/new_models/site.dart';
import '../../../new_views/common_widgets/app_filled_button.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';
import '../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../providers/gas_request_providers/site_provider.dart';
import '../../../providers/loading_list_notifier.dart';

class CreateDeviceTransferRequest extends StatefulWidget {
  static const String id = "/request-device-transfer";

  const CreateDeviceTransferRequest({Key? key}) : super(key: key);

  @override
  State<CreateDeviceTransferRequest> createState() => _CreateDeviceTransferRequestState();
}

class _CreateDeviceTransferRequestState extends State<CreateDeviceTransferRequest> {
  late DeviceTransferProvider _deviceTransferProvider;
  final DeviceTransfer _transferModel = DeviceTransfer(id: 0);
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  Asset _assetDestination = Asset();
  Asset? _pickedAsset;
  final List<GenericAttachmentModel> attachments = [];
  bool isInternal = true;
  PendingAssetServiceRequest? pendingAssetServiceRequest;

  @override
  void setState(VoidCallback fn) {
    if (mounted) super.setState(() {});
  }

  bool checkPendingRequest = false;

  void _onSubmit() async {
    _transferModel.assetId = _pickedAsset?.id;
    _transferModel.destSiteId = _assetDestination.site?.id;
    _transferModel.destBuildingId = _assetDestination.building?.id;
    _transferModel.destFloorId = _assetDestination.floor?.id;
    _transferModel.destDepartmentId = _assetDestination.department?.id;
    _transferModel.destRoomId = _assetDestination.room?.id;

    if (!_formKey.currentState!.validate() || !(await validateRequest())) {
      return;
    }
    _formKey.currentState!.save();
    List<GenericAttachmentModel> attachement = [];
    for (var item in attachments) {
      String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
      attachement.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType));
    }
    _transferModel.attachments = attachement;

    await _deviceTransferProvider.createRequest(
      context: context,
      model: _transferModel,
    );
    if (_deviceTransferProvider.stateCode == 200) {
      DashBoardProvider dashBoardProvider = Provider.of<DashBoardProvider>(context, listen: false);
      dashBoardProvider.refreshDashboard(context: context, userType: UsersTypes.nurse);
    }
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      //need to get internal and external request type data..
      await Provider.of<PpmServiceProvider>(context, listen: false).getData();
    });
    super.initState();
  }

  @override
  void dispose() {
    _deviceTransferProvider.reset();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _deviceTransferProvider = Provider.of<DeviceTransferProvider>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(
        title: context.translation.createAssetTransferRequest,
        titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  AssetPicker(
                      overWriteStyle: true,
                      device: _pickedAsset,
                      showLoading: false,
                      // borderColor: AppColor.black20,
                      // backgroundColor: AppColor.white936,
                      onPick: (asset) async {
                        _pickedAsset = asset;

                        if (_pickedAsset?.site != null && _transferModel.transferType?.value == 1) {
                          await _deviceTransferProvider.getSiteData(siteId: int.tryParse(_pickedAsset!.site!.id.toString()));
                          _assetDestination.site = _deviceTransferProvider.internalAssetDestination?.site;
                          _assetDestination.building = null;
                          _assetDestination.floor = null;
                          _assetDestination.department = null;
                        } else if (_pickedAsset?.site != null && _transferModel.transferType?.value == 2) {
                          _assetDestination.site = null;
                          _assetDestination.building = null;
                          _assetDestination.floor = null;
                          _assetDestination.department = null;
                        }

                        setState(() {});
                      }),
                  21.height,
                  requestTypeWidget(context),
                  12.height,
                  "Destination".bodyText(context).custom(color: context.isDark ? Colors.white : AppColor.white936),
                  12.height,
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SingleItemDropDownMenu<Site, SiteProvider>(
                        context: context,
                        title: context.translation.site,
                        initialValue: _assetDestination.site,
                        disableValue: isInternal ? null : _pickedAsset?.site,
                        showShadow: false,
                        loading: _deviceTransferProvider.isSiteLoading,
                        enabled: !isInternal,
                        backgroundColor: AppColor.fieldBgColor(context),
                        showAsBottomSheet: true,
                        onSelect: (value) {
                          _assetDestination.site = value;
                          _assetDestination.building = null;
                          _assetDestination.floor = null;
                          _assetDestination.department = null;
                          setState(() {});
                        },
                      ).expanded,
                      8.width,
                      SingleItemDropDownMenu<Building, NullableLoadingProvider>(
                        context: context,
                        title: context.translation.building,
                        initialValue: _assetDestination.building,
                        showShadow: false,
                        showAsBottomSheet: true,
                        backgroundColor: AppColor.fieldBgColor(context),
                        enabled: _assetDestination.site?.buildings?.isNotEmpty ?? false,
                        staticData: _assetDestination.site?.buildings ?? [],
                        onSelect: (value) {
                          _assetDestination.building = value;
                          _assetDestination.floor = null;
                          _assetDestination.department = null;
                          setState(() {});
                        },
                      ).expanded,
                    ],
                  ),
                  8.height,
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
                        context: context,
                        title: context.translation.floor,
                        showShadow: false,
                        showAsBottomSheet: true,
                        initialValue: _assetDestination.floor,
                        backgroundColor: AppColor.fieldBgColor(context),
                        enabled: _assetDestination.building?.floors?.isNotEmpty ?? false,
                        staticData: _assetDestination.building?.floors ?? [],
                        onSelect: (value) {
                          _assetDestination.floor = value;
                          _assetDestination.department = null;
                          setState(() {});
                        },
                      ).expanded,
                      8.width,
                      SingleItemDropDownMenu<Department, NullableLoadingProvider>(
                        context: context,
                        title: context.translation.department,
                        showShadow: false,
                        showAsBottomSheet: true,
                        initialValue: _assetDestination.department,
                        backgroundColor: AppColor.fieldBgColor(context),
                        enabled: _assetDestination.floor?.departments?.isNotEmpty ?? false,
                        staticData: _assetDestination.floor?.departments ?? [],
                        onSelect: (value) {
                          _assetDestination.department = value;
                          _assetDestination.room = null;
                          setState(() {});
                        },
                      ).expanded,
                    ],
                  ),
                  8.height,
                  AppTextFormField(
                    backgroundColor: AppColor.fieldBgColor(context),
                    labelText: context.translation.callComments,
                    labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                    alignLabelWithHint: true,
                    textInputType: TextInputType.multiline,
                    showShadow: false,
                    onSaved: (text) {
                      _transferModel.comment = text;
                    },
                  ),
                  8.height,
                  23.height,
                  AttachmentPicker(
                    label: context.translation.attachImage,
                    showAsListView: true,
                    attachment: attachments,
                    buttonColor: AppColor.black10,
                    onlyImages: false,
                    buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                  ),
                  // 100.height,
                ],
              ).toShadowContainer(context).paddingOnly(top: 20, start: 16, end: 16),
            ).expanded,
            FooterActionButton.footerContainer(
              context: context,
              child: AppFilledButton(buttonColor: AppColor.primary10, label: context.translation.submitRequest, maxWidth: true, onPressed: _onSubmit),
            ),
          ],
        ),
      ),
    );
  }

  Widget requestTypeWidget(BuildContext context) {
    return Consumer<PpmServiceProvider>(builder: (cxt, snapshot, _) {
      try {
        _transferModel.transferType ??= snapshot.items.first;
      } catch (ex) {
        print(ex);
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          context.translation.requestType.bodyText(context).custom(color: context.isDark ? Colors.white : AppColor.white936),
          8.height,
          Wrap(
            runSpacing: 8,
            spacing: 8,
            children: [
              for (var element in snapshot.items)
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: Radio(
                          value: element,
                          activeColor: AppColor.primary10,
                          fillColor: WidgetStateColor.resolveWith((states) {
                            if (states.contains(WidgetState.selected)) {
                              return AppColor.primary10; // Thumb color when selected
                            }
                            return Colors.grey; // Thumb color when unselected (grey)
                          }),
                          groupValue: _transferModel.transferType,
                          onChanged: (state) {
                            _transferModel.transferType = element;
                            isInternal = !isInternal;
                            if (isInternal) {
                              _assetDestination.site = _deviceTransferProvider.internalAssetDestination?.site;
                              _assetDestination.building = null;
                              _assetDestination.floor = null;
                              _assetDestination.department = null;
                            } else {
                              _assetDestination.site = null;
                              _assetDestination.building = null;
                              _assetDestination.floor = null;
                              _assetDestination.department = null;
                            }

                            setState(() {});
                            // });
                          }),
                    ),
                    8.width,
                    Text(element.name ?? '', style: AppTextStyles.tinyFont.copyWith(color: AppColor.neutral120)),
                  ],
                )
            ],
          ).toShimmer(isShow: snapshot.loading, context: context),
        ],
      );
    });
  }

  Future<bool> validateRequest() async {
    if (_pickedAsset == null) {
      await Fluttertoast.showToast(msg: "Please Select Asset");
      return false;
    }
    if (_assetDestination.site == null) {
      await Fluttertoast.showToast(msg: "Please Select Site");
      return false;
    }
    if (_assetDestination.building == null) {
      await Fluttertoast.showToast(msg: "Please Select Building");
      return false;
    }
    if (_assetDestination.floor == null) {
      await Fluttertoast.showToast(msg: "Please Select Floor");
      return false;
    }
    if (_assetDestination.department == null) {
      await Fluttertoast.showToast(msg: "Please Select Department");
      return false;
    }
    return true;
  }
}
