import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/asset_transfer_provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/employee/nurse_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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.dart';
import 'package:test_sa/models/employee.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/room_model.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/service_request_latest/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/views/widgets/equipment/asset_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/status/employee/nurse_menu.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';
import '../../widgets/equipment/pick_asset.dart';

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

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

  @override
  State<CreateAssetTransferRequest> createState() => _CreateAssetTransferRequestState();
}

class _CreateAssetTransferRequestState extends State<CreateAssetTransferRequest> {
  UserProvider? _userProvider;
  SettingProvider? _settingProvider;
  late AssetTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final AssetTransfer _transferModel = AssetTransfer();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController _receiverNameController = TextEditingController(), _commentsController = TextEditingController();
  final Asset _assetDestination = Asset();
  Asset? _pickedAsset;
  Employee? receiverEndUser;
  Employee? _selectedNurse;
  final List<File> _deviceImages = [];

  @override
  void setState(VoidCallback fn) {
    if (mounted) super.setState(() {});
  }
//TODO need to clean the extra logic and code when finilize api from backend..
  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;
    _transferModel.receiverEndUserId = _selectedNurse?.id;

    if (!_formKey.currentState!.validate() || !(await _transferModel.validate(context))) {
      return;
    }
    _formKey.currentState!.save();
    //  List<WorkOrderAttachments> attachement = [];
    //       for (var item in _deviceImages) {
    //         attachement.add(WorkOrderAttachments(id: 0, name: "${item.path.split("/").last}|${base64Encode(item.readAsBytesSync())}"));
    //       }

    await _deviceTransferProvider.createRequest(context: context, assetDestination: _transferModel, asset: _pickedAsset!);
  }

  List<Lookup> requestType = [
    Lookup(name: 'Internal', value: 1),
    Lookup(name: 'External', value: 2),
  ];

  @override
  void initState() {
    // TODO: need to check parameter with backend.
    // _deviceImages.addAll(_serviceRequest.devicePhotos!.map((e) => File(e)).toList());
    super.initState();
  }

  Lookup selectedRequestType = Lookup(name: 'Internal', value: 1);

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

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context, listen: false);
    _settingProvider = Provider.of<SettingProvider>(context, listen: false);
    _deviceTransferProvider = Provider.of<AssetTransferProvider>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      appBar: DefaultAppBar(title: context.translation.newTransferRequest),
      body: Form(
        key: _formKey,
        child: SafeArea(
          child: Column(
            children: [
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 16.height,
                    // PickAsset(
                    //   device: _pickedAsset,
                    //   onPickAsset: (asset) {
                    //     _pickedAsset = asset;
                    //     setState(() {});
                    //   },
                    // ),
                    AssetPicker(
                        device: _pickedAsset,
                        showLoading: false,
                        borderColor: AppColor.black20,
                        backgroundColor: AppColor.white936,
                        onPick: (asset) async {
                          _pickedAsset = asset;
                          setState(() {});
                          // pendingAssetServiceRequest = null;
                          // _serviceRequest.device = asset;
                          // await checkAssetForPendingServiceRequest(asset.id!.toInt());
                          // if (pendingAssetServiceRequest != null && pendingAssetServiceRequest!.details!.isNotEmpty) {
                          // showPendingRequestBottomSheet();
                        }),
                    21.height,
                    context.translation.requestType.bodyText(context).custom(color: AppColor.white936),
                    10.height,
                    Wrap(
                      runSpacing: 8,
                      spacing: 20,
                      children: [
                        for (var element in requestType)
                          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: selectedRequestType,
                                    onChanged: (state) {
                                      setState(() {
                                        selectedRequestType = element;
                                      });
                                    }),
                              ),
                              8.width,
                              Text(element.name ?? '', style: AppTextStyles.tinyFont.copyWith(color: AppColor.neutral120)),
                            ],
                          )
                      ],
                    ),
                    8.height,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SingleItemDropDownMenu<Site, SiteProvider>(
                          context: context,
                          title: context.translation.site,
                          initialValue: _assetDestination.site,
                          showShadow: false,
                          backgroundColor: AppColor.neutral100,
                          showAsBottomSheet: true,
                          onSelect: (value) {
                            _assetDestination.site = value;
                            _assetDestination.building = null;
                            _assetDestination.floor = null;
                            _assetDestination.department = null;
                            _selectedNurse = null;
                            Provider.of<NurseProvider>(context, listen: false).siteId = value!.id!.toInt();
                            Provider.of<NurseProvider>(context, listen: false).getData();
                            setState(() {});
                          },
                        ).expanded,
                        8.width,
                        SingleItemDropDownMenu<Building, NullableLoadingProvider>(
                          context: context,
                          title: context.translation.building,
                          initialValue: _assetDestination.building,
                          showShadow: false,
                          backgroundColor: AppColor.neutral100,
                          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,
                          initialValue: _assetDestination.floor,
                          backgroundColor: AppColor.neutral100,
                          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,
                          initialValue: _assetDestination.department,
                          backgroundColor: AppColor.neutral100,
                          enabled: _assetDestination.floor?.departments?.isNotEmpty ?? false,
                          staticData: _assetDestination.floor?.departments ?? [],
                          onSelect: (value) {
                            _assetDestination.department = value;
                            _assetDestination.room = null;
                            setState(() {});
                          },
                        ).expanded,
                      ],
                    ),
                    8.height,
                    // SingleItemDropDownMenu<Rooms, NullableLoadingProvider>(
                    //   context: context,
                    //   title: context.translation.room,
                    //   initialValue: _assetDestination.room,
                    //   backgroundColor:AppColor.neutral100,
                    //   enabled: _assetDestination.department?.rooms?.isNotEmpty ?? false,
                    //   staticData: _assetDestination.department?.rooms ?? [],
                    //   onSelect: (value) {
                    //     _assetDestination.room = value;
                    //     setState(() {});
                    //   },
                    // ),
                    // 8.height,
                    // NurseMenu(
                    //   title: context.translation.receiverName,
                    //   initialValue: _selectedNurse,
                    //
                    //   enable: _assetDestination.site != null,
                    //   onSelect: (employee) {
                    //     if (employee != null) {
                    //       _selectedNurse = employee;
                    //       setState(() {});
                    //     }
                    //   },
                    // ),
                    // 16.height,
                    AppTextFormField(
                      controller: _commentsController,
                      backgroundColor: AppColor.neutral100,
                      labelText: context.translation.callComments,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      alignLabelWithHint: true,
                      textInputType: TextInputType.multiline,
                      showShadow: false,
                      onSaved: (text) {
                        _transferModel.comment = text;
                      },
                    ),
                    8.height,
                    23.height,
                    MultiFilesPicker(
                      label: context.translation.attachImage,
                      files: _deviceImages,
                      buttonColor: AppColor.black10,
                      onlyImages: true,
                      buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.neutral120),
                    ),
                    // 100.height,
                  ],
                ).toShadowContainer(context).paddingOnly(top: 20, start: 16, end: 16),
              ).expanded,
              FooterActionButton.footerContainer(
                child: AppFilledButton(buttonColor: AppColor.primary10, label: context.translation.submitRequest, maxWidth: true, onPressed: _onSubmit
                    // buttonColor: AppColor.primary10,
                    ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
